【问题标题】:str_replace_all only getting firststr_replace_all 只获得第一
【发布时间】:2019-09-24 15:09:41
【问题描述】:

我正在尝试创建一个函数,将data.frame 的所有列重命名为蛇形案例。这是一个例子:

tibble("DateOfDeath" = NA,
       "Death" = NA,
       "Operative_Death" = NA) %>% 
  rename_all(function(x){str_replace_all(string = x, 
                                         pattern = '([[:alnum:]])([[:upper:]])([[:lower:]])', 
                                         replacement = '\\1_\\2\\3')}) %>% 
  rename_all(tolower)

我不太明白为什么我得到的是“date_ofdeath”而不是“date_of_death”。看起来字符串中还剩下一系列字母数字、大写和小写字母,但 str_replace_all 没有捕捉到它。

谢谢!

【问题讨论】:

  • 第一场比赛的下限与第二场比赛的 alnum 重叠。我认为您应该像在答案中那样使用蛇形库。
  • replacement = '\\1_\\2\\3_'
  • @MonkeyZeus 如果中间词超过 2 个字符,我认为这不会起作用。
  • 你应该提供一个更大的数据集来容纳你期望遇到的输入,并指出你的正则表达式失败的地方以及你期望的输出。

标签: r regex stringr


【解决方案1】:

您还可以使用 snakecase 库,它基本上是为这样的事情而设计的:

tibble("DateOfDeath" = NA,
       "Death" = NA,
       "Operative_Death" = NA) %>%
 rename_all(to_snake_case)

  date_of_death death operative_death
  <lgl>         <lgl> <lgl>          
1 NA            NA    NA     

【讨论】:

  • 谢谢。它解决了我的问题,但没有回答我的问题;)
猜你喜欢
  • 2012-04-22
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2018-06-01
相关资源
最近更新 更多