Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct variable names in select_

Tags:

r

dplyr

I am trying to write a function that will (in part) rename a variable by combining its source dataframe and 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 this programatically, something along the lines of:

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

This admittedly naive approach obviously doesn't work, but I haven't been able to figure it out. I'm sure the answer is somewhere in the nse vignette (https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html), but that doesn't seem to address constructing variable names.

like image 255
alexwhan Avatar asked Oct 09 '15 00:10

alexwhan


People also ask

How do you create a variable name in MATLAB?

A valid MATLAB variable name is a character vector of letters, digits, and underscores, such that the first character is a letter, and the length of the vector is less than or equal to the value returned by the namelengthmax function. Any character vector that exceeds namelengthmax is truncated in the varname output.


1 Answers

Not sure if this is the proper dplyr-esque way, but it'll 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
like image 138
Rich Scriven Avatar answered Sep 22 '22 11:09

Rich Scriven