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

Time:10-01

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.

CodePudding user response:

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)
  • Related