Konrad Konrad - 10 months ago 55
R Question

Capitalizing letters. R equivalent of excel "PROPER" function


I'm looking at a data frame resembling the extract below:

Month Provider Items
January CofCom 25
july CofCom 331
march vobix 12
May vobix 0

I would like to capitalise first letter of each word and lower the remaining letters for each word. This would result in the data frame resembling the one below:

Month Provider Items
January Cofcom 25
July Cofcom 331
March Vobix 12
May Vobix 0

In a word, I'm looking for R's equivalent of the ROPER function available in the MS Excel.

Answer Source

The question is about an equivalent of Excel PROPER and the (former) accepted answer is based on:

proper=function(x) paste0(toupper(substr(x, 1, 1)), tolower(substring(x, 2)))

It might be worth noting that:

proper("hello world")
## [1] "Hello world"

Excel PROPER would give, instead, "Hello World". For 1:1 mapping with Excel see @Matthew Plourde.

If what you actually need is to set only the first character of a string to upper-case, you might also consider the shorter and slightly faster version:

proper=function(s) sub("(.)", ("\\U\\1"), tolower(s), pe=TRUE)