Question

I have character vector which looks like this:

x <- c("cult", "brother sister relationship", "word title")

And I want to convert it to the lowerCamelCase style looking like this:

c("cult", "brotherSisterRelationship", "wordTitle")

I played around with gsub, gregexpr, strplit, regmatches and many other functions, but couldn't get a grip.

Especially two spaces in a character seem to be difficult to handle.

Maybe someone here has an idea how to do this.

Was it helpful?

Solution

> x <- c("cult", "brother sister relationship", "word title")
> gsub(" ([^ ])", "\\U\\1", x, perl=TRUE)
[1] "cult"                      "brotherSisterRelationship"
[3] "wordTitle"

Quoting from pattern matching and replacement:

For perl = TRUE only, it can also contain "\U" or "\L" to convert the rest of the replacement to upper or lower case and "\E" to end case conversion.

OTHER TIPS

A non-base alternative:

library(R.utils)
toCamelCase(x, capitalize = FALSE)
# [1] "cult"                      "brotherSisterRelationship" "wordTitle" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top