Dplyr: Using an expression to compute the new name in rename

Created on 27 Dec 2015  路  4Comments  路  Source: tidyverse/dplyr

This works to rename the demand column to demand2. Note we are using plyr's rename, not dplyr's rename:

library(dplyr)
num <- 2
BOD %>% plyr::rename(list(demand = paste0("demand", num)))  # ok

Since dplyr's rename uses new = old vs. plyr which uses old = new there is no easy way to do the above with dplyr's rename. This is pretty ugly but anyways it gives an error message:

library(dplyr)
num <- 2
BOD %>% do({ L <- setNames(list("demand"), paste0("demand", num)); rename_(., L) }) # bad

Also the following gives an error message since one cannot provide an expression where a name goes:

library(dplyr)
num <- 2
BOD %>% rename(list(paste0("demand", num) = demand))  # bad

Actually neither plyr's rename nor dplyr's rename are fully general since plyr can only easily handle expressions in the new name and dplyr in the old name. renameCol in the doBy package can handle expressions in both the old and the new name as it uses the syntax renameCol(indata, src, tgt) where src and tgt are character vectors of names and either of these or both can be complex expressions.

# rename column named paste0(base, num) to toupper(base)
# (In this case it renames column x2 to X)
library(dplyr)
base <- "x"
num <- 2
anscombe %>% doBy::renameCol(paste0(base, num), toupper(base))
feature

Most helpful comment

this should be:

dplyr::rename(mtcars, !! new_name := mpg)

Using := instead of = to allow for !! on the left-hand side.

All 4 comments

Will be possible once tidyeval conversion is complete. Syntax will look something like this:

old_var <- "x"
new_var <- "y"

df %>% rename(!!old_var ~ !!new_var)

We'll have plenty of documentation.

Hi all,

is this or a similar solution now implemented?

new_name <- "y"
mtcars %>% dplyr::rename( mpg ~ !!new_name  )

gives me the following error with dplyr version 0.7.4:

Error: All arguments must be named

Thanks,

Felix 聽

this should be:

dplyr::rename(mtcars, !! new_name := mpg)

Using := instead of = to allow for !! on the left-hand side.

thanks a bunch, that works. I simultaneously found it in vignette("programming"), very nicely written! Love the tidyverse.

Was this page helpful?
0 / 5 - 0 ratings