Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert not.camel.case to CamelCase in R

Tags:

In R, I want to convert

t1 <- c('this.text', 'next.text') "this.text" "next.text" 

to

'ThisText' 'NextText' 

I have tried

gsub('\\..', '', t1) 

But this gives me

"thisext" "nextext" 

as it does not replace the letter after the period.

Probably really easy but I can't work it out.

like image 838
Tom Liptrot Avatar asked Jul 26 '12 14:07

Tom Liptrot


People also ask

What is CamelCase conversion?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.

How do you use a CamelCase?

CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces. It is commonly used in web URLs, programming and computer naming conventions. It is named after camels because the capital letters resemble the humps on a camel's back.

What is CamelCase styling?

CamelCase (or camelCase) is a style of writing in which the writer avoids using spaces between consecutive words.


1 Answers

Alternatively a regex based solution:

t1 <- c('this.text', 'next.text')  # capitalize first letter t2 <- sub('^(\\w?)', '\\U\\1', t1, perl=T)  # remove points and capitalize following letter gsub('\\.(\\w?)', '\\U\\1', t2, perl=T) [1] "ThisText" "NextText" 

Edit: some explanations

sub('^(\\w?)', '\\U\\1', t1, perl=T), sub is sufficient here because we are only interested in the first match. Then the first alphanumeric character is matched at the beginning of each string with ^(\\w?). The parenthesis are needed for back reference in the replacement part of the function. For the replacement \\U is used to capitalize everything that comes afterwards (which is the first character).

The same principle is applied in gsub('\\.(\\w?)', '\\U\\1', t2, perl=T) with the only difference that not the first character is matched, but every ..

like image 51
johannes Avatar answered Oct 12 '22 19:10

johannes