schlusie
schlusie

Reputation: 2017

Convert character to lowerCamelCase in R

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.

Upvotes: 2

Views: 124

Answers (2)

Henrik
Henrik

Reputation: 67778

A non-base alternative:

library(R.utils)
toCamelCase(x, capitalize = FALSE)
# [1] "cult"                      "brotherSisterRelationship" "wordTitle" 

Upvotes: 7

devnull
devnull

Reputation: 123508

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

Upvotes: 11

Related Questions