如何在R中绘制线性回归? [英] how to plot the linear regression in R?
本文介绍了如何在R中绘制线性回归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在R中进行以下线性回归的情况
I want to make the following case of linear regression in R
year<-rep(2008:2010,each=4)
quarter<-rep(1:4,3)
cpi<-c(162.2,164.6,166.5,166.0,166.4,167.0,168.6,169.5,170.0,172.0,173.3,174.0)
plot(cpi,xaxt="n",ylab="CPI",xlab="")
axis(1,labels=paste(year,quarter,sep="C"),at=1:12,las=3)
fit<-lm(cpi~year+quarter)
我想画一条线来显示我处理的数据的线性回归.我尝试过:
I want to plot the line that shows the linear regression of the data that I process. I have tried with:
abline(fit)
abline(fit$coefficients[[1]],c(fit$coefficients[[2]],fit$coefficients[[3]]))
问题在于我的公式的格式为:
The problem is that my formula is of the form:
y=a+b*year+c*quarter
而不是像这样简单的东西:
and not something simpler like:
y=a+b*year
那我怎么画那条显示线性回归的线呢?
so how I can draw that line that shows the linear regression?
可以用abline画线吗?
Is it possible to draw the line with abline?
推荐答案
您是否正在寻找predict
函数?
例如:使用lines(predict(fit))
将给出:
您还可以使用它来预测与计算出的系数一致的未来数据.例如
You could also use this for predicting future data aligning with the calculated coefficients. E.g.
# plot the existing data with space for the predicted line
plot(c(cpi,rep(NA,12)),xaxt="n",ylab="CPI",xlab="",ylim=c(162,190))
# plot the future predictions as a line using the next 3 year periods
lines(13:24,
predict(
fit,
newdata=data.frame(year=rep(c(2011,2012,2013),each=4),quarter=rep(1:4,3))
)
)
year<-rep(2008:2013,each=4)
axis(1,labels=paste(year,quarter,sep="C"),at=1:24,las=3)
这篇关于如何在R中绘制线性回归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文