14

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
mt1022
  • 16,834
  • 5
  • 48
  • 71

1 Answers1

26

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’
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • 21
    Or slightly shorter `df %>% rename_at(vars(col.from), ~col.to)` – talat Jun 09 '17 at 08:23
  • Wow, both are very simple in syntax. The only thing is that it is hard for me to unstand the `rename_at`'s behavior under such case. I thought the `.funs` would be applied to each colname in `.vars`. I didn't expect it will match by position. – mt1022 Jun 09 '17 at 08:41
  • 1
    @mt1022 Yep, the one from @docendodiscimus would make a good example in the `?select_all` doc. The function is applied to all selected column names. That means, `function(x)` basically receives the `col.from` values in `x`, then it can do stuff with it - which is in our case just returning a different character vector of length 3. – lukeA Jun 09 '17 at 08:47