简体   繁体   English

预测R中的lm函数(多元线性回归)

[英]predict lm function in R (multiple linear regression)

I did a multiple linear regression in R using the function lm and I want to use it to predict several values. 我使用函数lm在R中进行了多元线性回归,我想用它来预测多个值。 So I'm trying to use the function predict() . 所以我正在尝试使用函数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...) . 所以我想预测t=c(10,20,30...)时p的值。 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 " “ model.frame.default(Terms,newdata,na.action = na.action,xlev = object $ xlevels)中的错误:变量长度不同(为'vart'找到)。此外:警告消息:'newdata'有3行但是找到的变量有132行”

132 is the length of my vector of variables upon which I run the regression. 132是我进行回归的变量向量的长度。 I checked my vector 1/t and it is well-defined and has the right number of coefficients. 我检查了我的矢量1 / t,它定义明确,并且系数数量正确。 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. 提前致谢。

The problem is you defined v as a new, distinct variable from t when you fit your model. 问题是当您拟合模型时,您将v定义为与t不同的新变量。 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. R不会记住变量的创建方式,因此在拟合模型时它不知道vt的函数。 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. 因此,当您预测值时,它将使用v的现有值,该现有值的长度与您指定的t的新值的长度不同。

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 . 如果您确实希望v是一个完全独立的变量,那么您还需要在new data.frame中为v提供值,以预测p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM