0 votes
1 view
in R Programming by (5.3k points)
recategorized by

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.



# [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")

1 Answer

0 votes
by (25.3k points)

To perform capitalization of first letters, you can use the toupper() function from the base R package as follows:

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

Caps <- function(x) {

  s <- strsplit(x, " ")[[1]]

  paste(toupper(substring(s, 1,1)), substring(s, 2),

        sep="", collapse=" ")


sapply(name, Caps)

zip code         state   final count 

"Zip Code"       "State" "Final Count" 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !