预测函数和data.frame的错误

时间:2014-11-10 16:49:02

标签: r dataframe predict

我是R的新手,所以我可能只是因为不理解R的底层结构而犯了一个新手的错误,但我已经阅读了关于这个主题的所有问题,但似乎仍然无法获得我的代码工作。

我从这里开始: how to solve predict.lm() error: variable 'affinity' was fitted with type "nmatrix.1" but type "numeric" was supplied

然后我读到了这个: https://stat.ethz.ch/pipermail/r-help/2008-August/170848.html

但我仍然无法使我的预测值成为正确的data.frame。

问题在于:我正在使用R附带的mtcars数据集。我已经制作了基本模型:

fitcars<-lm(mpg~wt, data=mtcars)

然后我尝试这样做:

predict(fitcars,data.frame(wt=c(3)),interval=("prediction")) 

获得在一定重量下预测mpg的置信区间。但是,我继续得到错误:

variable 'center.wt' was fitted with type "nmatrix.1" but type "numeric" was supplied.

如果我第一次as.vector(mtcars$wt),那无关紧要。

我甚至试图按照以上帖子的建议做这个修复:

fitcars<-lm(mpg~as.vector(center.wt), data=mtcars) 

我刚收到这个错误:

Error in model.frame.default(formula = mpg ~ as.vector(center.wt), data = mtcars,  : 
  invalid type (list) for variable 'as.vector(center.wt)'

我很难过,知道我只是犯了一个愚蠢的错误。有人可以帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

嗯,我似乎没有问题:

fitcars<-lm(mpg~wt,data=mtcars)
new<-data.frame(wt=2.5)
predict(fitcars,new,interval='prediction')