[R] how to transform string to "Camel Case"?

Gabor Grothendieck ggrothendieck at gmail.com
Mon Apr 15 16:56:38 CEST 2013


On Mon, Apr 15, 2013 at 2:50 AM, Liviu Andronic <landronimirc at gmail.com> wrote:
> Dear all,
> Given the following vector:
>> (z <- c('R project', 'hello world', 'something Else'))
> [1] "R project"      "hello world"    "something Else"
>
> I know how to obtain all capitals or all lower case letters:
>> tolower(z)
> [1] "r project"      "hello world"    "something else"
>> toupper(z)
> [1] "R PROJECT"      "HELLO WORLD"    "SOMETHING ELSE"
>
> I saw the tocamel() function in 'rapport', but it doesn't do what I
> want to achieve as it actually proceeds to camelCase/CamelCase the
> strings:
>> tocamel(z)
> [1] "RProject"      "helloWorld"    "somethingElse"
>
>
> But how should I proceed to obtain Camel Case? Here's what I'd like to get:
> c('R Project', 'Hello World', 'Something Else')
>

Here is a one liner using gsubfn from the gsubfn package
(http://gsubfn.googlecode.com).  gsubfn is like gsubfn except the
second argument can be a function (or a list or a proto object).  The
regular expression here matches a space followed by any character.
For each such match gsubfn will call the function denoted by the
second argument using the two parenthesized portions of the regular
expression as the two arguments.  It supports an optional formula
notation to express the function for compactness so ... ~ toupper(..2)
denotes function(...) toupper(..2) which is equivalent to function(x,
y) toupper(y) .  It replaces the input with the output of that
function.  Finally we check if any of the components of the input are
NA and replace those with NA in the output:

> replace(gsubfn("( )(.)", ... ~ toupper(..2), z), is.na(z), NA)
[1] "RProject"      "helloWorld"    "somethingElse" NA



More information about the R-help mailing list