Moving Variable Name to Data Columns

I am trying to create a function that can pass variable name to column names for the data.frame file that will be created in this 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 so that "Var1" is automatically placed before "Dummy" in each of the variable names? Ideally I would get 3 variables that look like this ...

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

      

+3


source to share


1 answer


Try the below code. The key is in deparse(substitute)

. I also changed your function to not use the global assignment operator <<-

, which is bad 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)

      

+4


source







All Articles