使用 dplyr rename(across( [英] Renaming multiple columns with dplyr rename(across(

查看:14
本文介绍了使用 dplyr rename(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

We can use rename_with instead of 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 语法更改单个变量的名称;rename_with() 使用函数重命名列.

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

并在?across

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 rename(across(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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