The explicit formula used in linear regression

I have a list of formulas and I use lapply and lm to create a list of regression models. However, when I look at the call component of each linear model, instead of seeing the explicit formula, I see the name of the variable that I analyzed in the linear model. For instance. using the mtcars dataset:

 temp_formula_list = list(as.formula(hp~1),as.formula(hp~cyl)) temp_fm_list = lapply(temp_formula_list, function(x) lm(data = mtcars, formula = x)) 

Then consider call of temp_fm_list[[2]] :

 temp_fm_list[[2]]$call 

gives

 lm(formula = x, data = mtcars) 

when I would like to explicitly indicate

 lm(formula = hp~cyl, data = mtcars) 
+4
source share
1 answer

You can do some simple language calculations using bquote to build your challenge.

  temp_fm_list = lapply(temp_formula_list, function(x) { lmc <- bquote( lm(data = mtcars, formula = .(x))) eval(lmc) }) temp_fm_list # Call: # lm(formula = hp ~ 1, data = mtcars) # # Coefficients: # (Intercept) # 146.7 # # # [[2]] # # Call: # lm(formula = hp ~ cyl, data = mtcars) # # Coefficients: # (Intercept) cyl # -51.05 31.96 

note that

 function(x) do.call('lm', list(formula = x, data = quote(mtcars)) 

Will also work


Other approaches ....

Even with your initial call, you can recreate the formula from the terms object associated with the model

eg,

 x <- hp ~ cyl lmo <- lm(formula = x, data = mtcars) formula(lmo) ## hp ~ cyl lmo$call # lm(formula = x, data = mtcars) 

You can use this call object if you want (although this is a pretty dangerous practice)

 # for example lmo$call$formula <- x lmo$call ## lm(formula = hp ~ cyl, data = mtcars) ## however you can create rubbish here too lmo$call$formula <- 'complete garbage' lmo$call ## lm(formula = "complete garbage", data = mtcars) # but, being careful, you could use it appropriately temp_fm_list = lapply(temp_formula_list, function(x) { oo <- lm(data = mtcars, formula = x) oo$call$formula <-x oo }) temp_fm_list # Call: # lm(formula = hp ~ 1, data = mtcars) # # Coefficients: # (Intercept) # 146.7 # # # [[2]] # # Call: # lm(formula = hp ~ cyl, data = mtcars) # # Coefficients: # (Intercept) cyl # -51.05 31.96 
+10
source

All Articles