一起使用 dplyr rename_at 和 stringr str_replace 重命名列时出错
Error when using dplyr rename_at and stringr str_replace together to rename columns
我想使用 str_replace 重命名几个具有特定前缀的变量。
我 运行 正在处理下面用 REPREX 描述的问题:
test <- tibble::tribble(~pre_a, ~pre_b, ~c,
1,2,3,
4,5,6)
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')),
stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
错误:
Error in get(.x, .env, mode = "function") : object 'c(1, 4)' of
mode 'function' was not found In addition: Warning message: In
stri_replace_first_regex(string, pattern,
fix_replacement(replacement), : argument is not an atomic vector;
coercing
问题仅出在 str_replace,因为如果我使用基本 R 函数,它将起作用:
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')), toupper)
注意:我不只是想转换成大写,所以我需要使用str_replace函数。
使用自定义函数时需要使用~
表示法。
library(dplyr)
test %>%
dplyr::rename_at(dplyr::vars(starts_with('pre')),
~stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
此外,rename_at
现在已替换为 rename_with
。
test %>%
dplyr::rename_with(~stringr::str_replace(.,pattern = 'pre',replacement ='PRE'),
dplyr::starts_with('pre'))
# A tibble: 2 x 3
# PRE_a PRE_b c
# <dbl> <dbl> <dbl>
#1 1 2 3
#2 4 5 6
我想使用 str_replace 重命名几个具有特定前缀的变量。 我 运行 正在处理下面用 REPREX 描述的问题:
test <- tibble::tribble(~pre_a, ~pre_b, ~c,
1,2,3,
4,5,6)
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')),
stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
错误:
Error in get(.x, .env, mode = "function") : object 'c(1, 4)' of mode 'function' was not found In addition: Warning message: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), : argument is not an atomic vector; coercing
问题仅出在 str_replace,因为如果我使用基本 R 函数,它将起作用:
test %>%dplyr::rename_at(., dplyr::vars(starts_with('pre')), toupper)
注意:我不只是想转换成大写,所以我需要使用str_replace函数。
使用自定义函数时需要使用~
表示法。
library(dplyr)
test %>%
dplyr::rename_at(dplyr::vars(starts_with('pre')),
~stringr::str_replace(., pattern = 'pre', replacement ='PRE'))
此外,rename_at
现在已替换为 rename_with
。
test %>%
dplyr::rename_with(~stringr::str_replace(.,pattern = 'pre',replacement ='PRE'),
dplyr::starts_with('pre'))
# A tibble: 2 x 3
# PRE_a PRE_b c
# <dbl> <dbl> <dbl>
#1 1 2 3
#2 4 5 6