2

Say I have the following data frame:

a <- c("Paul v. the man", "Molly v. the Bear")
df <- data.frame(a)

And I want to accomplish the following:

I want to turn "Paul v. the man" to "Paul v. The Man," which I tried to use the following:

library(tools)
df <- toTitleCase(df$a)

How do I make sure "the" doesn't become lowercase?

I also want to turn "Molly v. the Bear" to "Molly v. The Bear."

Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
hy9fesh
  • 589
  • 2
  • 15
  • If you run just `tools:: toTitleCase` you can see the code for that function. There's no option to change just a word, but you could copy the code and edit to make your own custom version. Just take out "the" from the `lpat` regular expression line. – MrFlick Nov 18 '22 at 20:39

1 Answers1

1

Use toTitleCase on a single word. Here we also make sure that words below 3 characters are left as is.

library(tools)

sapply(strsplit(df$a, " "), function(x) 
  paste(ifelse(nchar(x) > 2, toTitleCase(x), x), collapse = " "))
[1] "Paul v. The Man"   "Molly v. The Bear"
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29