使用dplyr的rename_*条件重命名变量

3

假设我想通过在所有以数字开头的变量名之前添加前缀来有条件地重命名变量。但是,在使用rename_*函数进行操作时,我遇到了错误。

library(dplyr)
library(stringr)

ds <- 
  tibble(
    `4 grade` = c(1,2,3),
    `6 grade` = c(1,2,3),
    `G8 grade` = c(1,2,3),
  )

ds

# my function works with rename_all
ds %>% rename_all( ~ paste0("G", .) )

# but when I try to apply my function conditionally I get an error
ds %>% rename_at( vars(starts_with("[[:digit:]]")), ~paste0("G", .) )
ds %>% rename_at( vars(str_detect("^[[:digit:]]")), ~paste0("G", .) )
ds %>% rename_if( str_detect("^[[:digit:]]"), ~paste0("G", .) )

我如何使用条件逻辑和rename_*来指定要重命名的变量?
3个回答

4

有一个名为matchestidyselect帮助函数,可以在变量名称上启用正则表达式搜索。请注意,starts_with无法工作,因为它仅接受字符串文本:

library(dplyr)

ds %>%
  rename_at(vars(matches("^[0-9]")), ~ paste0("G", .))

输出:

# A tibble: 3 x 3
  `G4 grade` `G6 grade` `G8 grade`
       <dbl>      <dbl>      <dbl>
1          1          1          1
2          2          2          2
3          3          3          3

2

一个可能性是:

最初的回答。

ds %>%
 rename_at(grep("^[0-9]", names(.), value = TRUE), list(~ paste0("G", .)))

  `G4 grade` `G6 grade` `G8 grade`
       <dbl>      <dbl>      <dbl>
1          1          1          1
2          2          2          2
3          3          3          3

2

一个可能性(重新分配名称)。正如@IceCreamToucan所建议的那样,我们实际上不需要捕获第二个组,因此在原始正则表达式中不需要\\2部分。

  names(ds) <- ds %>% 
   names() %>% 
  str_replace_all(.,"(^[0-9])(\\s+)","G\\1") 
 ds
# A tibble: 3 x 3
  `G4 grade` `G6 grade` `G8 grade`
       <dbl>      <dbl>      <dbl>
1          1          1          1
2          2          2          2
3          3          3          3

正如 @IceCreamToucan 建议的那样,我们可以使用 rename_all 来保持与 OP 相同的逻辑。

ds %>% 
rename_all(str_replace_all, "(^[0-9])", "G\\1")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接