【发布时间】:2021-10-02 04:13:58
【问题描述】:
我想将列中每个单词的第一个字母大写,而不将其余字母转换为小写。我正在尝试使用stringr,因为它是矢量化的并且可以很好地处理数据帧,但也会使用另一种解决方案。下面是一个表示我想要的输出和各种尝试的表示。我只能选择第一个字母,但不知道如何大写。感谢您的帮助!
我还查看了相关帖子,但不确定如何在我的案例中应用这些解决方案(即在数据框中):
Capitalize the first letter of both words in a two word string
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
#> 3 Golden Ratio 1.61
#> 4 Nothing 0
# Some attempts
mutate(words, word = str_replace_all(word, "(?<=^|\\s)([a-zA-Z])", "X"))
#> # A tibble: 4 x 2
#> word number
#> <chr> <dbl>
#> 1 Xroblems 99
#> 2 Xnswer 42
#> 3 Xolden Xatio 1.61
#> 4 XOTHING 0
mutate(words, word = str_replace_all(word, "(?<=^|\\s)([a-zA-Z])", "\\1"))
#> # A tibble: 4 x 2
#> word number
#> <chr> <dbl>
#> 1 problems 99
#> 2 Answer 42
#> 3 golden ratio 1.61
#> 4 NOTHING 0
由reprex package (v2.0.0) 于 2021 年 7 月 26 日创建
【问题讨论】:
标签: r string stringr uppercase