【问题标题】:Error/warning message related to definition of newdata in predict.lm与 predict.lm 中的 newdata 定义相关的错误/警告消息
【发布时间】: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


    【解决方案1】:

    如果您想预测,请始终将 data.frame 传递给 lm

    a     <- mtcars$mpg
    x     <- data.matrix(cbind(mtcars$wt, mtcars$hp))
    DF <- data.frame(a, x)
    xTest <- x[2,]  # We will use this for prediction later
    fitCar <-lm(a ~ ., data = DF) 
    
    yPred <- predict(fitCar, newdata = data.frame(X1 = xTest[1], X2 = xTest[2]) , interval="confidence")
    #       fit      lwr      upr
    #1 22.58348 21.51622 23.65074
    

    【讨论】:

    • 谢谢罗兰。但是,用于查找 yPred 的建议解决方案(即 predict(fitCar, newdata = data.frame(X1 = xTest[1], X2 = xTest[2]), interval="confidence") )是不可扩展的。例如,x 和 xTest 有 1000 列(即 1000 个特征/预测变量),这意味着我们必须编写 X1 = xTest[1], x2 = xTest[2], ..., x1000 = xTest[1000]。我想知道是否有办法解决它。
    • data.frame(x[2,, drop = FALSE])
    • Roland:如果 xTest = x[2,],上述建议的解决方案是适用的。但是,它不适用于一般情况,例如 xTest
    • 只需创建一个data.frame:data.frame(t(xTest))。这真的是基本的东西。请去学习一些教程。
    • 我希望它像那样简单。为了确保我们在同一页面上,这是我们正在处理的内容:xTest &lt;- as.numeric(cbind(4,5)),然后我们使用以下命令进行预测:predict(fitCar, newdata = data.frame(t(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 1 row but variables found have 32 rows
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2016-02-21
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多