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