Search code examples
rstringtext

Capitalize first word in a multiword string in R


In R, how to capitalize only the first word in each string in a vector of single and multi-worded strings? The solutions I found (stringr::str_to_sentence(), stringr::str_to_title(), capitalize every word in the string.

Thanks!

strings <- c('one', 'one two', 'three four', 'five six')
expected.result <- c('One', 'One two', 'Three four', 'Five six')

Solution

  • strings <- c("one", "one two", "three four five", "six seven")
    

    stringr::str_to_sentence(strings)
    [1] "One"             "One two"         "Three four five" "Six seven"      
    

    Base R:

    sub("(\\w)", "\\U\\1", strings, perl = TRUE)
    [1] "One"             "One two"         "Three four five" "Six seven"