Suppose that I want to fit a simple LR model for each predictor in the Boston
data set to predict crime rates (crim
), and to save these fitted models in a list so I can later iterate over them.
library(MASS)
names(Boston)
Output: 'crim' 'zn' 'indus' 'chas' 'nox' 'rm' 'age' 'dis' 'rad' 'tax' 'ptratio' 'black' 'lstat' 'medv'
The following
reg_list <- list()
i <- 1
for (name in names(Boston)[2:14]) {
reg_list[[i]] <- lm(crim~name, data=Boston)
i <- i+1
}
results in an error:
Error in model.frame.default(formula = crim ~ name, data = Boston, drop.unused.levels = TRUE): variable lengths differ (found for 'name') Traceback: 1. lm(crim ~ name, data = Boston) 2. eval(mf, parent.frame()) 3. eval(mf, parent.frame()) 4. stats::model.frame(formula = crim ~ name, data = Boston, drop.unused.levels = TRUE) 5. model.frame.default(formula = crim ~ name, data = Boston, drop.unused.levels = TRUE)
What is this error and how can I get around it?