Search code examples
rlaglm

Calculate linear regression slope with moving window


I have a dataframe and i need to automate the slope calculation by lm each 5 rows and jump 1 point and calculate slope with next 5 points and again jump 1 point and calculate slope with 5 points. And if the end of datafra when you not have 5 points put NA or no calculate slope

mtcars[c(1:5),c(1,3)] %>% mutate(slope = lm(c(mpg) ~ c(disp))$coefficients[[2]])

I need to calculate slope to next 5 points with gap = 1

mtcars[c(2:6),c(1,3)] %>% mutate(slope = lm(c(mpg) ~ c(disp))$coefficients[[2]])


Solution

  • Using map to iterate over each row number:

    # toy dataset
    data <- tibble(
            x = 1:50,
            y = rnorm(50))
    
    data %>% 
            # for each row, get the coefficient of the independent variable (i.e the coefficient of x)
            mutate(model = c(map(1:(nrow(data) - 4), ~lm(y ~ x, data = data[.x:(.x + 4), ])$coefficients[2]), NA, NA, NA, NA) %>% unlist())
    
    # A tibble: 50 × 3
           x       y   model
       <int>   <dbl>   <dbl>
     1     1 -2.52    0.775 
     2     2 -0.455   0.370 
     3     3 -0.914   0.333 
     4     4 -1.14    0.221 
     5     5  1.70   -0.214 
     6     6  0.0893  0.0863
     7     7  0.138  -0.305 
     8     8  0.748  -0.329 
     9     9  0.298  -0.239 
    10    10  0.441   0.274 
    # ℹ 40 more rows