问题描述
嘿,我正在尝试通过在新版本的dplyr中添加“ Last_”来重命名某些列,但我一直收到此错误
Error: `across()` must only be used inside dplyr verbs.
这是我的代码
data %>% rename(across(everything(),~paste0("Last_",.)))
dplyr版本:v1.0.2
解决方法
我们可以使用rename_with
代替rename
library(dplyr)
library(stringr)
data %>%
rename_with(~str_c("Last_",.),everything())
可复制的示例
data(iris)
head(iris) %>%
rename_with(~str_c("Last_",.cols = everything())
# Last_Sepal.Length Last_Sepal.Width Last_Petal.Length Last_Petal.Width Last_Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
#6 5.4 3.9 1.7 0.4 setosa
根据?rename
rename()使用new_name = old_name语法更改各个变量的名称; named_with()使用函数来重命名列。
和?across
across()可以轻松地将相同的转换应用于多个对象 列,允许您在summarise()中使用select()语义 和mutate()。
该说明说它在mutate/summarise
(和transmute
?)内使用,没有任何其他功能使用的指示,即如果select
从小插图('colwise')(或参见https://cran.r-project.org/web/packages/dplyr/vignettes/colwise.html)
“ across()不适用于select()或rename(),因为它们已经使用了整洁的选择语法;如果要使用函数转换列名,则可以使用rename_with()。”