Search code examples
rstatisticseconomics

Calculate and plot residuals variance of a regression, per year, using R


I calculated a linear model, with the lm() function. I know how to extract the residuals, using the resid() function, but I would like to calculate the values of the residuals variance by year and plot it.


Solution

  • You could use a data frame out of the residuals and the year, aggreagte it and make a barplot.

    fdf <- data.frame(resid=fit$residuals, year=fit$model$year)
    res <- aggregate(resid ~ year, fdf, var)
    barplot(resid ~ year, res)
    

    enter image description here


    Toy data

    set.seed(42)
    dat <- transform(cbind.data.frame(year=1:5, x=rnorm(500)), y=.5 * x + rnorm(500))
    fit <- lm(y ~ x + year, dat)