简体   繁体   中英

How to use predict from a model stored in a list in R?

I have a dataframe dfab that contains 2 columns that I used as argument to generate a series of linear models as following:

models = list()
for (i in 1:10){
    models[[i]] = lm(fc_ab10 ~ (poly(nUs_ab, i)), data = dfab)
}

dfab has 32 observations and I want to predict fc_ab10 for only 1 value.

I thought of doing so:

newdf = data.frame(newdf = nUs_ab)
newdf[] = 0
newdf[1,1] = 56
prediction = predict(models[[1]], newdata = newdf)

First I tried writing newdf as a dataframe with only one position, but since there are 32 in the dataset on which the model was built, I thought I had to provide at least 32 points as well. I don't think this is necessary though.

Every time I run that piece of code I am given the following error:

Error: variable 'poly(nUs_ab, i) was fitted with type “nmatrix.1” but type “numeric” 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

I thought all I need to use predict was a LM model, predictors (the number 56) given in a column-named dataframe. Obviously, I am mistaken.

How can I fix this issue?

Thanks.

newdf should be a data.frame with column name nUs_ab , otherwise R won't be able to know which column to operate upon (ie, generate the prediction design matrix). So the following code should work

newdf = data.frame(nUs_ab = 56)
prediction = predict(models[[1]], newdata = newdf)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM