将两个单词字符串中两个单词的首字母大写

问题描述:

假设我有一个两个单词的字符串,我想大写两个.

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

Hmisc 包有一个函数 capitalize 将第一个单词大写,但我不确定如何使第二个单词大写.capitalize 的帮助页面并未表明它可以执行该任务.

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"

我想得到:

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

三字串呢:

name2 <- c("I like pizza")

执行大写的基本 R 函数是 toupper(x).在 ?toupper 的帮助文件中有这个功能可以满足您的需求:

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"