我有一个小写的字符串向量.我想将它们改为标题案例,这意味着每个单词的第一个字母都会被大写.我已经设法用一个双循环来做,但我希望有一个更有效和优雅的方式来做到这一点,也许是一个单行gsub
和一个正则表达式.
这里有一些示例数据,以及有效的双循环,其次是我尝试过的其他不起作用的东西.
strings = c("first phrase", "another phrase to convert",
"and here's another one", "last-one")
# For each string in the strings vector, find the position of each
# instance of a space followed by a letter
matches = gregexpr("\\b[a-z]+", strings)
# For each string in the strings vector, convert the first letter
# of each word to upper case
for (i in 1:length(strings)) {
# Extract the position of each regex match for the string in row …
Run Code Online (Sandbox Code Playgroud) 我想将列中每个单词的第一个字母大写,而不将其余字母转换为小写。我正在尝试使用它,stringr
因为它是矢量化的并且可以很好地与数据帧配合使用,但也会使用另一种解决方案。下面是一个表示,显示了我想要的输出和各种尝试。我只能选择第一个字母,但不知道如何将其大写。感谢您的帮助!
我还查看了相关帖子,但不确定如何在我的案例中应用这些解决方案(即在数据框中):
library(dplyr)
library(stringr)
words <-
tribble(
~word, ~number,
"problems", 99,
"Answer", 42,
"golden ratio", 1.61,
"NOTHING", 0
)
# Desired output
new_words <-
tribble(
~word, ~number,
"Problems", 99,
"Answer", 42,
"Golden Ratio", 1.61,
"NOTHING", 0
)
# Converts first letter of each word to upper and all other to lower
mutate(words, word = str_to_title(word))
#> # A tibble: 4 x 2
#> word number
#> <chr> <dbl>
#> 1 Problems 99
#> 2 Answer 42 …
Run Code Online (Sandbox Code Playgroud) 我试图将列中的所有数据转换为“第一个字母为大写”以下代码将所有数据替换为第一行,
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
allDestination$Categories <- simpleCap(allDestination$Categories)
Run Code Online (Sandbox Code Playgroud)
样本数据
japan/okinawa/okinawa-other-islands
japan/hokkaido/hokkaido-north/furano-biei-tomamu
japan/hokkaido/hokkaido-north/asahikawa-sounkyo
japan/hokkaido/hokkaido-north/wakkanai-rishiri-rebun
japan/hokkaido/hokkaido-east/kushiro-akan-nemuro
Run Code Online (Sandbox Code Playgroud)
功能代码示例从 首字母到大写
如何使函数“列兼容”而不是仅替换单个值?