r - 如何在R中绘制线性回归?

标签 r linear-regression

我想在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)

我想画一条线来显示我处理的数据的线性回归。我尝试过:
abline(fit)
abline(fit$coefficients[[1]],c(fit$coefficients[[2]],fit$coefficients[[3]]))

问题是我的公式的形式为:
y=a+b*year+c*quarter

而不是更简单的东西:
y=a+b*year

那么如何绘制显示线性回归的线呢?

可以用abline画线吗?

最佳答案

您在寻找predict函数吗?

例如:使用lines(predict(fit))将产生:

您也可以使用它来预测与计算出的系数一致的 future 数据。例如。

# 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 - 如何在R中绘制线性回归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14451782/

相关文章:

machine-learning - 线性回归的梯度下降不收敛

r - 为什么我在 Shiny 应用程序上的图像崩溃了?

r - 安装可供所有用户使用的 R 软件包

r - 更改绘图轴上刻度线的间距?

numpy - Python向量没有列大小?/Theta初始化为全0

python - 类中的 NaN

r - 如何从 lm 摘要中隐藏控制变量

r - 用 R data.table 行的排列填充 "count matrix"

r - 按序列分割向量

rcs 在 lm() 模型中生成错误的预测