Search code examples
rregression

Access variable names in call from dynamic formula in model


Wondering if there's any way to access and/or store variable names in a call from a dynamic formula. example:

run_model <- function(datas){
  model <-  lm(data = datas, formula = bmi~age)
  model
  
}

test <- run_model(nhanes)
test$call

Test$call does not include "nhanes" but "datas".

I tried searching through all of the parts of the model object and didn't find anything. Not sure if I'm missing something OR if there's a way to alter the call within my function to store the variable names.


Solution

  • The call object is the literal call made to lm inside your function, and is captured without substituting any of the variable names used inside the function.

    You can create a list of call arguments yourself and substitute the correct name in. Then you can invoke lm using do.call:

    run_model <- function(datas) {
      do.call('lm', list(formula = bmi ~ age, data = substitute(datas)),
              envir = parent.frame())
    }
    
    test <- run_model(nhanes)
    test$call
    #> lm(formula = bmi ~ age, data = nhanes)