RH2015
RH2015

Reputation: 141

Piping variable name into dataframe columns

I've been trying to create a function that can pipe the name of a variable into the names of columns for a data.frame that will be created in that function.

For example:

#Create variable
Var1 <- c(1,1,2,2,3,3)


#Create function that dummy codes the variable and renames them
rename_dummies <- function(x){
    m <- model.matrix(~factor(x))
    colnames(m)[1] <- "Dummy1"
    colnames(m)[2] <- "Dummy2"
    colnames(m)[3] <- "Dummy3"  
    m <<- data.frame(m)  
 }

rename_dummies(Var1)

Now, what can I add to this function that that "Var1" is automatically placed in front of "Dummy" in each of the variable names? Ideally I would end up with 3 variables that look like this...

> names(m)
[1] "Var1_Dummy1" "Var1_Dummy2" "Var1_Dummy3"

Upvotes: 3

Views: 553

Answers (1)

Josh W.
Josh W.

Reputation: 1143

Try the below code. The key is in deparse(substitute). I also modified your function to not use the global assignment operator <<-, which is poor practice.

Var1 <- c(1,1,2,2,3,3)


#Create function that dummy codes the variable and renames them
rename_dummies <- function(x){
  nm = deparse(substitute(x))
  m <- model.matrix(~factor(x))
  colnames(m)[1] <- "Dummy1"
  colnames(m)[2] <- "Dummy2"
  colnames(m)[3] <- "Dummy3"  
  m <- data.frame(m)  
  names(m) <- paste(nm, names(m), sep = "_")
  m
}

rename_dummies(Var1)

Upvotes: 4

Related Questions