使用dplyr重命名重命名多列(across( [英] Renaming multiple columns with dplyr rename(across(

查看:147
本文介绍了使用dplyr重命名重命名多列(across(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试通过添加"Last_"来重命名某些列使用新版本的dplyr,但我不断收到此错误

Hey i'm trying to rename some columsn by adding "Last_" with the new version of dplyr but I keep getting this error

Error: `across()` must only be used inside dplyr verbs.

这是我的代码

data %>% rename(across(everything(), ~paste0("Last_", .)))

dplyr版本:v1.0.2

dplyr version: 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()使用函数来重命名列.

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

这篇关于使用dplyr重命名重命名多列(across(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆