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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With