简体   繁体   中英

Residual Plot for multivariate regression in Time Series, with time on X axis in R

I have a dataframe which is a time series. I am using the function lm to build a multivariate regression model.

linearmodel <- lm(Y~X1+X2+X3, data = data)
  1. I want to plot the residuals of this linearmodel on the y-axis and time on the x-axis using a simple function, with the lm() object as the input.
  2. Standard residual plotting functions like the one in car package ( car::residualPlot ) gives residuals on the Y-axis and fitted-values on the Y-axis.
  3. Ideally, I need the residuals on the Y-axis and the timescale on the X-axis. But I understand that the function lm() is time agnositc. So, I can live with if the residuals are on Y-axis in the same order as the data input and nothing on the X-axis
  4. Is there a plotting function which i can use by passing the linearmodel object into the function (not something where i can extract the residuals and use ggplot2). So for example: plot<- plotresidualsinorder(linearmodels) should give me the residuals on Y-axis in the same order of the data input?
  5. I want to use this plot in R-shiny ultimately.

My research led me to car package, which is wonderful in its own right, but doesn't have the function to solve my problem.

Many thanks in advance for the help.

You can use the Residual Plot information. For the proposed solution, we need to apply the lm function to a formula that describes your Y variables by the variables X1+X2+X3 , and save the linear regression model in a new linearmodel variable. Finally, we compute the residual with the resid function. In your case, the following solution can be representative for your problem.

Proposed solution:

linearmodel <- lm(Y~X1+X2+X3, data = data)
lm_resid <- resid(linearmodel)
plot(data$X1+X2+X3, lm_resid, 
    ylab="Residuals", xlab="Time", 
    main="Data") 
abline(0, 0)

For any help concerning how does the resid function works, you can try:

help(resid)

Calisto's solution will work, but there is a more simple and straightforward solution. The lm function already give to you the regression residuals. So you may simply pass:

plot(XTime, linearmodel$residuals, main = "Residuals")

XTime is the Date variable of your dataset, maybe you may require to format that with POSIX functions: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/as.POSIX*

Add parameters as you need to share it on R-shiny.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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