【问题标题】:`stringr` to convert first letter only to uppercase in dataframe`stringr` 仅将数据框中的第一个字母转换为大写
【发布时间】:2021-10-02 04:13:58
【问题描述】:

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

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

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 年 7 月 26 日创建

【问题讨论】:

    标签: r string stringr uppercase


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,我知道如何将您的解决方案集成到我的管道中:mutate(words, word = gsub("\\b([a-z])", "\\U\\1", word, perl=TRUE))
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我们可以使用 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 
      

      【讨论】:

      • 好主意,谢谢!但是,这仍然会遗漏诸如“nOTHING”之类的词 - 但是,请记住使用 ifelse 包装的建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多