Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename multiple columns given character vectors of column names and replacement [duplicate]

Tags:

r

dplyr

While this is easy to do with base R or setnames in data.table or rename_ in dplyr 0.5. Since rename_ is deprecated, I couldn't find an easy way to do this in dplyr 0.6.0.

Below is an example. I want to replace column name in col.from with corresponding values in col.to:

col.from <- c("wt", "hp", "vs")
col.to <- c("foo", "bar", "baz")

df <- mtcars
head(df, 2)
#>               mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4

Expected output:

names(df)[match(col.from, names(df))] <- col.to
head(df, 2)
#>               mpg cyl disp bar drat   foo  qsec baz am gear carb
#> Mazda RX4      21   6  160 110  3.9 2.620 16.46   0  1    4    4
#> Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02   0  1    4    4

How can I do this with rename or rename_at in dplyr 0.6.0?

like image 563
mt1022 Avatar asked Jun 09 '17 07:06

mt1022


1 Answers

I don't know if this is the right way to approach it, but

library(dplyr)
df %>% rename_at(vars(col.from), function(x) col.to) %>% head(2)
#               mpg cyl disp bar drat   foo  qsec baz am gear carb
# Mazda RX4      21   6  160 110  3.9 2.620 16.46   0  1    4    4
# Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02   0  1    4    4

Also note that I live in the future:

# packageVersion("dplyr")
# # [1] ‘0.7.0’
like image 135
lukeA Avatar answered Oct 21 '22 23:10

lukeA