Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to capitalize the first word in a string (base)

Tags:

regex

r

Using the base install functions what is the fastest way to capitalize the first letter in a vector of text strings?

I have provided a solution below but it seems to be a very inefficient approach (using substring and pasting it all together). I'm guessing there's a regex solution I'm not thinking of.

Once I have a few responses I'll benchmark them and report back the fastest solution using microbenchmarking.

Thank you in advance for your help.

x <- c("i like chicken.", "mmh so good", NA)
#desired output
[1] "I like chicken." "Mmh so good"     NA  
like image 209
Tyler Rinker Avatar asked Dec 13 '22 01:12

Tyler Rinker


1 Answers

I didn't time it, but I bet this is pretty fast

capitalize <- function(string) {
    #substring(string, 1, 1) <- toupper(substring(string, 1, 1))
    substr(string, 1, 1) <- toupper(substr(string, 1, 1))
    string
}
capitalize(x)
#[1] "I like chicken." "Mmh so good"     NA 
like image 169
GSee Avatar answered Jan 19 '23 11:01

GSee