【发布时间】:2015-07-08 07:47:36
【问题描述】:
在使用 predict.lm 时,我收到一条错误消息或不正确的解决方案,我正在尝试了解可能导致这种情况的原因。
在这里发布我的问题之前,我已经阅读了几个与我的问题类似的解决方案,如example 所示。但是,这些问题的解决方案中建议的方法似乎在这里不起作用,我正在尝试找出原因以及如何解决它。
为了最好地解释我的问题,请考虑以下 MWE:
#------------------------------
# Fit least squares model
#------------------------------
data(mtcars)
a <- mtcars$mpg
x <- data.matrix(cbind(mtcars$wt, mtcars$hp))
xTest <- x[2,] # We will use this for prediction later
fitCar <-lm(a ~ x)
#------------------------------
# Prediction for x = xTest
#------------------------------
# Method 1 (doesn't work)
yPred <- predict(fitCar, newdata = data.frame(x = xTest) , interval="confidence")
Error: variable 'x' was fitted with type "nmatrix.2" but type "numeric" was supplied
# Method 2 (works, but as you may observe, it is incorrect)
yPred <- predict(fitCar, newdata = data.frame(xTest) , interval="confidence")
fit lwr upr
1 23.572329 22.456232 24.68843
2 22.583483 21.516224 23.65074
3 25.275819 23.974405 26.57723
4 21.265020 20.109318 22.42072
....
....
Warning message:
'newdata' had 2 rows but variables found have 32 rows
问题:假设我们想要找到与 xTest 对应的 yPred,那么正确的方法是什么?
【问题讨论】:
标签: r least-squares predict