1

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?

adibender
  • 7,288
  • 3
  • 37
  • 41
user315830
  • 13
  • 3
  • 2
    Try `reg_list[[i]] <- lm(as.formula(paste("crim ~", name)), data=Boston)` instead of `reg_list[[i]] <- lm(crim~name, data=Boston)`. I'm sure this is a duplicate, though it may take a minute to find it. The problem is the way `formula`s work -- it thinks you want a variable named `name`, not a variable with the value stored in `name`. So, you use the workaround I mentioned. – duckmayr Feb 09 '19 at 16:55
  • 2
    Thank you very much @duckmayr, that's it. :) – user315830 Feb 09 '19 at 17:12

0 Answers0