Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming multiple columns with dplyr rename(across(

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.

this is my code

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

dplyr version: v1.0.2

like image 557
Ian.T Avatar asked Oct 03 '20 20:10

Ian.T


People also ask

How do I rename multiple columns in dplyr?

rename() is the method available in the dplyr library which is used to change the multiple columns (column names) by name in the dataframe. The operator – %>% is used to load the renamed column names to the dataframe. At a time it will change single or multiple column names.

How do I change a column name in R rename?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector.


2 Answers

We can use rename_with instead of rename

library(dplyr)   
library(stringr)
data %>%
      rename_with(~str_c("Last_", .), everything())

Reproducible example

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

According to ?rename

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

and in ?across

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

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

like image 74
akrun Avatar answered Oct 16 '22 11:10

akrun


From the vignette('colwise') (or see the web version).

"across() doesn’t work with select() or rename() because they already use tidy select syntax; if you want to transform column names with a function, you can use rename_with()."

like image 7
Rtist Avatar answered Oct 16 '22 11:10

Rtist