Rename multiple columns based on character vectors of column names and replace

Although it is easy to do with a base of R or setnames in data.tableor rename_at dplyr0.5. Since it is rename_deprecated, I could not find an easy way to do this in dplyr0.6.0.

The following is an example. I want to replace the column name in the col.fromcorresponding 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 Result:

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 to do this with renameor rename_atin dplyr0.6.0?

+4
source share
1 answer

I don’t know if this is suitable for him, 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’
+9
source

Source: https://habr.com/ru/post/1678851/


All Articles