how to plot the linear regression in R?

前端 未结 5 1618
时光取名叫无心
时光取名叫无心 2020-12-14 23:43

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         


        
5条回答
  •  余生分开走
    2020-12-15 00:09

    Are you looking for the predict function?

    E.g.: using lines(predict(fit)) will give:

    enter image description here

    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)
    

    enter image description here

提交回复
热议问题