循环动态创建模型公式

时间:2019-02-09 16:52:30

标签: r list linear-regression

假设我想为Boston数据集中的每个预测变量拟合一个简单的LR模型,以预测犯罪率(crim),并将这些拟合的模型保存在列表中,以便以后使用遍历他们。

library(MASS)
names(Boston)
Output: 
'crim' 'zn' 'indus' 'chas' 'nox' 'rm' 'age' 'dis' 'rad' 'tax' 'ptratio' 'black' 'lstat' 'medv'

以下

reg_list <- list()
i <- 1
for (name in names(Boston)[2:14]) {
    reg_list[[i]] <- lm(crim~name, data=Boston)
    i <- i+1
}

导致错误:

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)

这是什么错误,我该如何解决?

0 个答案:

没有答案