Build variable names in select_

I am trying to write a function that (partially) renames a variable by combining its original data frame and the existing variable name. In essence, I want:

df1 <- data.frame(a = 1, b = 2) 

to become:

 df1 %>% rename(df1_a = a) # df1_a b #1 1 2 

But I want to do it programmatically, something like:

 fun <- function(df, var) { outdf <- rename_(df, paste(df, var, sep = "_") = var) return(outdf) } 

This admittedly naive approach obviously does not work, but I could not understand it. I'm sure the answer is somewhere in the nse vignette ( https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html ), but that does not seem to affect the construction of variable names.

+6
source share
2 answers

Not sure if this is dplyr-esque's right way, but it will get you going.

 fun <- function(df, var) { x <- deparse(substitute(df)) y <- deparse(substitute(var)) rename_(df, .dots = with(df, setNames(as.list(y), paste(x, y, sep = "_")))) } fun(df1, a) # df1_a b # 1 1 2 fun(df1, b) # a df1_b # 1 1 2 
+8
source

lazyeval is really not needed here, because the environment of both inputs is known. It is said:

 library(lazyeval) library(dplyr) library(magrittr) fun = function(df, var) { df_ = lazy(df) var_ = lazy(var) fun_(df_, var_) } fun_ = function(df_, var_) { new_var_string = paste(df_ %>% as.character %>% extract(1), var_ %>% as.character %>% extract(1), sep = "_") dots = list(var_) %>% setNames(new_var_string) df_ %>% lazy_eval %>% rename_(.dots = dots) } fun(df1, a) 
0
source

All Articles