Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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.

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

1 Answer

0 votes
by

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" 

Browse Categories

...