我试图将多个lm对象存储在一个列表中。例如,我拟合1、2、3阶的3个简单多项式回归,并通过for循环将它们添加到列表中。
lm_results <- list()
for (i in 1:3){
lm_results[[i]] <- lm(mpg~poly(horsepower, i),
data=Auto)
}
我的操作一定有问题,因为predict()
函数仅适用于列表的最后一个对象,即lm_results[[3]]
对于lm_results[[1]]
,我收到一条错误和一条警告消息:
predict(lm_results[[1]], Auto)
Error: variable 'poly(horsepower, i)' was fitted with type "nmatrix.2" but
type "nmatrix.3" was supplied
In addition: Warning message:
In Z/rep(sqrt(norm2[-1L]), each = length(x)) :
longer object length is not a multiple of shorter object length
对于lm_results[[2]]
,仅显示警告消息:
predict(lm_results[[2]], Auto)
Error: variable 'poly(horsepower, i)' was fitted with type "nmatrix.1" but
type "nmatrix.3" was supplied
最奇怪的是,如果我“手动”执行相同操作(见下文),一切都会正常。
lm_results <- list()
lm_results[[1]] <- lm(mpg~poly(horsepower, 1),
data=Auto)
lm_results[[2]] <- lm(mpg~poly(horsepower, 2),
data=Auto)
lm_results[[3]] <- lm(mpg~poly(horsepower, 3),
data=Auto)
您对问题可能有什么想法?
谢谢。
答案 0 :(得分:1)
使用lapply
可以为我解决问题:
lm_results <- lapply(1:3, function(x) lm(mpg ~ poly(horsepower, x), data = Auto))