Convert To Proper Case Except If It's A TLA In R

Viewed 78

I HAVE A SERIES OF CHARACTER VALUES THAT LOOK LIKE THIS. I Want Them To Look Like This.

I have a set of words however that, when matched exactly, should remain as they are. In this list would be things like ABC.

For the input

SIX SIXTY TEST SUBJECT

with exclusion "SIX"

The desired output would be "SIX Sixty Test Subject".

My current code is this:

x <- gsub(paste0("(", paste(exclusions, collapse = "|"), "|\\w)(\\w*)"), "\\U\\1\\L\\2", x, perl = T)
2 Answers

Here is one approach:

x <- "SIX SIXTY TEST SUBJECT"
output <- gsub("(?<=.)\\b(\\S)(\\S*)", "\\U\\1\\L\\2", x, perl=TRUE)
output

[1] "SIX Sixty Test Subject"

Here is an explanation of the regex used:

(?<=.)   assert that some text precedes (ignore the first uppercase word)
\\b     word boundary
(\\S)   match and capture the first character
(\\S*)  match and capture the remaining characters

Then we replace with the first captured letter in uppercase followed by the remaining characters in lowercase. Note that the positive lookahead (?<=.) will spare the very first word from the replacement.

Edit:

If instead you want to spare the literal word SIX, then use this version:

x <- "SIX SIXTY TEST SUBJECT"
output <- gsub("\\b(?!SIX\\b)(\\S)(\\S*)\\b", "\\U\\1\\L\\2", x, perl=TRUE)

Use the to_any_case function from the snakecase package, passing your exclusions to the abbreviations argument.

library(snakecase)
x <- "SIX SIXTY TEST SUBJECT"
exclusions <- c("SIX")
to_any_case(x, case = "title", abbreviations = exclusions)
#> [1] "SIX Sixty Test Subject"
Related