tidyverse / dplyr

dplyr: A grammar of data manipulation
https://dplyr.tidyverse.org/
Other
4.75k stars 2.12k forks source link

Using an expression to compute the new name in rename #1600

Closed ggrothendieck closed 7 years ago

ggrothendieck commented 8 years ago

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))
hadley commented 7 years ago

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.

FelixTheStudent commented 6 years ago

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    

lionel- commented 6 years ago

this should be:

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

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

FelixTheStudent commented 6 years ago

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