Search code examples
rstringtitle-case

Capitalize the first letter of both words in a two word string


Let's say that I have a two word string and I want to capitalize both of them.

name <- c("zip code", "state", "final count")

The Hmisc package has a function capitalize which capitalized the first word, but I'm not sure how to get the second word capitalized. The help page for capitalize doesn't suggest that it can perform that task.

library(Hmisc)
capitalize(name)
# [1] "Zip code"    "State"       "Final count"

I want to get:

c("Zip Code", "State", "Final Count")

What about three-word strings:

name2 <- c("I like pizza")

Solution

  • The base R function to perform capitalization is toupper(x). From the help file for ?toupper there is this function that does what you need:

    simpleCap <- function(x) {
      s <- strsplit(x, " ")[[1]]
      paste(toupper(substring(s, 1,1)), substring(s, 2),
          sep="", collapse=" ")
    }
    
    name <- c("zip code", "state", "final count")
    
    sapply(name, simpleCap)
    
         zip code         state   final count 
       "Zip Code"       "State" "Final Count" 
    

    Edit This works for any string, regardless of word count:

    simpleCap("I like pizza a lot")
    [1] "I Like Pizza A Lot"