简体   繁体   English

如何使用根据存储在R中的列表中的模型进行预测?

[英]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: 我有一个数据框架dfab ,其中包含2列,我将它们用作生成一系列线性模型的参数,如下所示:

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. dfab有32个观察值,我只想预测1个值的fc_ab10。

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. 首先,我尝试将newdf编写为仅具有一个位置的数据框,但是由于构建模型的数据集中有32个位置,因此我认为我也必须至少提供32个点。 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. 错误:变量'poly(nUs_ab,i)符合类型“ nmatrix.1”,但提供了“数值”类型。 In addition: Warning message: In Z/rep(sqrt(norm2[-1L]), each = length(x)) : longer object length is not a multiple of shorter object length 另外:警告消息:在Z / rep(sqrt(norm2 [-1L])中,每个= length(x)):较长的对象长度不是较短的对象长度的倍数

I thought all I need to use predict was a LM model, predictors (the number 56) given in a column-named dataframe. 我以为我需要使用的预测是LM模型,在以列命名的数据框中给出的预测变量(数字56)。 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). newdf应该是列名称为nUs_ab ,否则R将无法知道要对哪一列进行操作(即生成预测设计矩阵)。 So the following code should work 所以下面的代码应该工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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