Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit formula used in linear regression

Tags:

r

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 I parsed into the linear model. E.g. 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 examining the call of temp_fm_list[[2]]:

temp_fm_list[[2]]$call

gives

lm(formula = x, data = mtcars)

when I would like it to explicitly give

lm(formula = hp~cyl, data = mtcars)
like image 605
Alex Avatar asked Dec 26 '22 06:12

Alex


1 Answers

You can do some simple computing on the language using bquote to construct your call.

 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))

Would also work


Other approaches....

Even with your original 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 mess with this call object if you wish (although this is rather 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  
like image 135
mnel Avatar answered Dec 28 '22 20:12

mnel