Search code examples
rregressionzoorolling-computation

Create column with rolling linear model coefficients


I need to perform a rolling linear regression of 24 months between a variable and time and save the B1 coefficient on a column. I can do the rolling regression but I don't know how to save the B1 results in my original dataframe. Here is a reproducible example:

date <- seq(as.Date("2011-01-01"), as.Date("2012-01-01"), by="days")

set.seed(8)
df <- as.data.frame(date) %>%
  mutate(value = runif(366, min = 0, max = 100))

#Estimate rolling linear regression coef when t = 24
nr <- nrow(df)
reg <- function(ix) coef(lm(value ~ date, df, subset = ix)); rollapplyr(1:nr, 24, reg, fill = NA)

#How to save B1 results in a column of the data frame?

Does anybody knows how to do this? Thanks in advance!


Solution

  • Assuming that B1 means the slope of the regression line:

    df %>% 
      mutate(slope = rollapplyr(1:n(), 24, function(ix) reg(ix)[[2]], fill = NA))
    

    Update

    x was supposed to be ix. Also used n() to avoid using nr. Have fixed.