predict lm function in R (multiple linear regression)

只谈情不闲聊 提交于 2019-12-02 16:18:21

问题


I did a multiple linear regression in R using the function lm and I want to use it to predict several values. So I'm trying to use the function predict(). Here is my code:

new=data.frame(t=c(10, 20, 30))
v=1/t
LinReg<-lm(p ~ log(t) + v)
Pred=predict(LinReg, new, interval="confidence")

So I would like to predict the values of p when t=c(10,20,30...). However, this is not working and I don't see why. The error message I get is:

"Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : variable lengths differ (found for 'vart') In addition: Warning message: 'newdata' had 3 rows but variables found have 132 rows "

132 is the length of my vector of variables upon which I run the regression. I checked my vector 1/t and it is well-defined and has the right number of coefficients. What is curious is that if I do a simple linear regression (of one variable), the same code works well...

new=data.frame(t=c(10, 20, 30))
LinReg<-lm(p ~ log(t))
Pred=predict(LinReg, new, interval="confidence")

Can anyone help me please! Thanks in advance.


回答1:


The problem is you defined v as a new, distinct variable from t when you fit your model. R doesn't remember how a variable was created so it doesn't know that v is a function of t when you fit the model. So when you go to predict values, it uses the existing values of v which would have a different length than the new values of t you are specifying.

Instead you want to fit

new <- data.frame(t=c(10, 20, 30))
LinReg <- lm(p ~ log(t) + I(1/t))
Pred <- predict(LinReg, new, interval="confidence")

If you did want v to be a completely independent variable, then you would need to supply values for v as well in your new data.frame in order to predict p.



来源:https://stackoverflow.com/questions/29658298/predict-lm-function-in-r-multiple-linear-regression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!