How to convert a vector of strings to Title Case

前端 未结 5 1258
长情又很酷
长情又很酷 2021-01-11 19:00

I have a vector of strings in lower case. I\'d like to change them to title case, meaning the first letter of every word would be capitalized. I\'ve managed to do it with a

5条回答
  •  清歌不尽
    2021-01-11 19:29

    The main problem is that you're missing perl=TRUE (and your regex is slightly wrong, although that may be a result of flailing around to try to fix the first problem).

    Using [:lower:] instead of [a-z] is slightly safer in case your code ends up being run in some weird (sorry, Estonians) locale where z is not the last letter of the alphabet ...

    re_from <- "\\b([[:lower:]])([[:lower:]]+)"
    strings <- c("first phrase", "another phrase to convert",
                 "and here's another one", "last-one")
    gsub(re_from, "\\U\\1\\L\\2" ,strings, perl=TRUE)
    ## [1] "First Phrase"              "Another Phrase To Convert"
    ## [3] "And Here's Another One"    "Last-One"    
    

    You may prefer to use \\E (stop capitalization) rather than \\L (start lowercase), depending on what rules you want to follow, e.g.:

    string2 <- "using AIC for model selection"
    gsub(re_from, "\\U\\1\\E\\2" ,string2, perl=TRUE)
    ## [1] "Using AIC For Model Selection"
    

提交回复
热议问题