hy9fesh
hy9fesh

Reputation: 661

How to create exceptions for toTitleCase()?

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."

Upvotes: 2

Views: 71

Answers (1)

Andre Wildberg
Andre Wildberg

Reputation: 19088

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"

Upvotes: 1

Related Questions