问题
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