`stringr` 仅将数据框中的第一个字母转换为大写

`stringr` to convert first letter only to uppercase in dataframe

我想将列中每个单词的第一个字母大写,而不将其余字母转换为小写。我正在尝试使用 stringr,因为它已矢量化并且可以很好地处理数据帧,但也会使用另一种解决方案。下面是一个显示我想要的输出和各种尝试的代表。我只能 select 第一个字母,但不知道如何将其大写。感谢您的帮助!

我还查看了相关帖子,但不确定如何在我的案例中应用这些解决方案(即在数据框中):

First letter to upper case

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-07-26 创建

这是使用 gsub 的基础 R 解决方案:

words$word <- gsub("\b([a-z])", "\U\1", words$word, perl=TRUE)

这会将每个单词的第一个小写字母替换为其大写版本。请注意,\b 字边界将匹配前面有空格或列值开头的小写字母。

根据 https://community.rstudio.com/t/is-there-will-there-be-perl-support-in-stringr/38016/3 stringr 使用 stringi 和 ICU 引擎,因此它不支持也不会支持 perl 类型的正则表达式(这是在其他答案中启用 \U 部分的原因)。所以你应该使用 gsub with perl=TRUE @Tim 的回答。

我们可以使用 stringr 包中的 str_to_title 函数。

问题是NOTHING变成了Nothing

但我们可以通过 ifelse -> 检查第一个字符是否为大写,然后将其他字符设为大写。

library(dplyr)
library(stringr)
words %>% 
    mutate(word = ifelse(str_detect(word, "^[:upper:]+$"), word,str_to_title(word)))

输出:

  word         number
  <chr>         <dbl>
1 Problems      99   
2 Answer        42   
3 Golden Ratio   1.61
4 NOTHING        0