2
预测考虑到可以通过创建模型列表:机型不能在
fits = vector(mode="list",length=10)
for(i in 1:10)
{
fits[[i]] = lm(nox~poly(dis,i),data=Boston)
}
其中,用于Boston
数据集,可以在MASS
库中找到。现在
,为了做出预测:
dislim = range(Boston$dis)
dis.grid = seq(from = dislim[1],to = dislim[2],by = 0.1)
这样做是为了给在其nox
的值预测的dis
值。 现在,为了作出预测,我们可以做到以下几点:
predict(fits[[1]],list(dis = dis.grid))
但是这将导致一个错误:
Error: variable 'poly(dis, i)' was fitted with type "nmatrix.1" but type "nmatrix.10" 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.Boston = lm(nox~poly(dis,3),data=Boston)
lm.Boston.pred = predict(lm.Boston,list(dis = dis.grid))
它工作正常。那么,为什么我不能在列表中这样做呢?
要展开对此,@ mooncrater代码的问题是'poly(dis,i)'中的'i'被捕获为模型中的一个变量。因此,可以使用像predict(fits [[1]],list(dis = dis.grid,i = 1))这样的每个模型。但这不是很有用。 –
你也可以用'lm(bquote(nox〜poly(dis,。(i))),data = Boston)'而不是'paste()'来建立公式。 – MrFlick