预测R中的lm函数(多元线性回归) [英] predict lm function in R (multiple linear regression)
问题描述
我使用函数lm在R中进行了多元线性回归,我想用它来预测多个值.因此,我正在尝试使用功能predict()
.
这是我的代码:
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")
所以我想预测t=c(10,20,30...)
时p的值.但是,这不起作用,我不明白为什么.我收到的错误消息是:
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:
"model.frame.default中的错误(术语,newdata,na.action = na.action,xlev = object $ xlevels):可变长度不同(适用于"vart") 另外:警告消息: 'newdata'有3行,但找到的变量有132行"
"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是我进行回归的变量向量的长度.我检查了我的矢量1/t,它定义明确,并且系数数量正确.奇怪的是,如果我对一个变量进行简单的线性回归,则相同的代码可以很好地工作...
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.
推荐答案
问题是,当您拟合模型时,您将v
定义为与t
不同的新变量. R不记得如何创建变量,因此在拟合模型时它不知道v
是t
的函数.因此,当您预测值时,它会使用现有的v
值,该值与您指定的新的t
值具有不同的长度.
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.
相反,您想适应
new <- data.frame(t=c(10, 20, 30))
LinReg <- lm(p ~ log(t) + I(1/t))
Pred <- predict(LinReg, new, interval="confidence")
如果您确实希望v
是一个完全独立的变量,那么您还需要在new
data.frame中提供<c2>的值,以便预测p
.
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
.
这篇关于预测R中的lm函数(多元线性回归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!