且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用dplyr重命名重命名多列(across(

更新时间:2023-01-01 11:36:09

我们可以使用 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()使用函数来重命名列.

rename() changes the names of individual variables using new_name = old_name syntax; rename_with() renames columns using a function.

中的整个

across()可以轻松地将相同的转换应用于多个对象列,允许您在summarise()中使用select()语义和mutate().

across() makes it easy to apply the same transformation to multiple columns, allowing you to use select() semantics inside in summarise() and mutate().

描述说它在 mutate/summarise (和 transmute ?)中使用,并且没有任何其他功能使用的迹象,即,如果 select,它将失败

The description says its use within mutate/summarise (and transmute?), and no indication of usage with any other functions i.e. it would fail with select