Home > other >  Store assigned variable name of dataset in function
Store assigned variable name of dataset in function

Time:06-06

I want to dynamically use the variable name of any dataset within a function. The catch is that it has to work within any loop and paste function because I want to iterate the name over each row of data. Quite naturally, if I do this:

some_fun <- function(data){
print(substitute(data))
}
some_fun(teengamb)
>"teengamb"

Then It works and I get the result that I want. However, If I were to do the following:

some_fun <- function(data){
  print(map(data, function(x)paste(x,",",substitute(data))))
}
some_fun(gamble_formula)

>$formulas
 [1] "gamble ~ status , data"                         "gamble ~ sex , data"                           
 [3] "gamble ~ status   income , data"                "gamble ~ verbal   sex , data"                  
 [5] "gamble ~ sex   status , data"                   "gamble ~ status   income   verbal , data"      
 [7] "gamble ~ income   verbal   sex , data"          "gamble ~ verbal   sex   status , data"         
 [9] "gamble ~ sex   status   income , data"          "gamble ~ status   income   verbal   sex , data"

I should have 'gamble_formula', appended rather than 'data'. Here's the example data I am working with:

structure(list(formulas = c("gamble ~ status", "gamble ~ sex", 
"gamble ~ status   income", "gamble ~ verbal   sex", "gamble ~ sex   status", 
"gamble ~ status   income   verbal", "gamble ~ income   verbal   sex", 
"gamble ~ verbal   sex   status", "gamble ~ sex   status   income", 
"gamble ~ status   income   verbal   sex")), class = "data.frame", row.names = c(NA, 
-10L))

CodePudding user response:

Using eval.

some_fun <- function(data) {
 d <- substitute(data)
 paste0(eval(d)$formulas, ', ', d)
}
some_fun(gamble_formula)
# [1] "gamble ~ status, gamble_formula"                         "gamble ~ sex, gamble_formula"                           
# [3] "gamble ~ status   income, gamble_formula"                "gamble ~ verbal   sex, gamble_formula"                  
# [5] "gamble ~ sex   status, gamble_formula"                   "gamble ~ status   income   verbal, gamble_formula"      
# [7] "gamble ~ income   verbal   sex, gamble_formula"          "gamble ~ verbal   sex   status, gamble_formula"         
# [9] "gamble ~ sex   status   income, gamble_formula"          "gamble ~ status   income   verbal   sex, gamble_formula"
  •  Tags:  
  • r
  • Related