R:for循环将多个lm对象存储在列表中

时间:2018-11-28 14:49:48

标签: r list for-loop lm

我试图将多个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) 

您对问题可能有什么想法?

谢谢。

1 个答案:

答案 0 :(得分:1)

使用lapply可以为我解决问题:

lm_results <- lapply(1:3, function(x) lm(mpg ~ poly(horsepower, x), data = Auto))