“Rolling” Regression in R

断了今生、忘了曾经 提交于 2019-12-04 20:00:53

Define a function which returns the year and R squared given a subset of rows of df (without ID) and then use rollapply with it.

library(dplyr)
library(zoo)

R2 <- function(x) {
  x <- as.data.frame(x)
  c(YEAR = tail(x$YEAR, 1), R2 = summary(lm(DV ~ IV, x))$r.squared)
}

df %>%
  group_by(ID) %>%
  do(data.frame(rollapply(.[-1], 20, by = 4, R2, by.column = FALSE))) %>%
  ungroup

giving:

# A tibble: 12 x 3
   ID     YEAR      R2
   <fct> <dbl>   <dbl>
 1 1      2005 0.0133 
 2 1      2006 0.130  
 3 1      2007 0.0476 
 4 1      2008 0.0116 
 5 1      2009 0.00337
 6 1      2010 0.00570
 7 2      2005 0.0481 
 8 2      2006 0.00527
 9 2      2007 0.0158 
10 2      2008 0.0303 
11 2      2009 0.235  
12 2      2010 0.116  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!