R: Grouped rolling window linear regression with rollapply and ddply

穿精又带淫゛_ 提交于 2019-12-02 04:40:06

1) rollapply works on data frames too so it is not necessary to convert df to zoo.

2) lm uses na.action, not na.rm, and its default is na.omit so we can just drop this argument.

3) rollapplyr is a more concise way to write rollapply(..., align = "right").

Assuming that rolled otherwise does what you want and incorporating these changes into rolled, the ddply statement in the question should work or we could use by from the base of R which we show below:

rolled <- function(df) {
    rollapplyr(df, width = 6, function(m) { 
          coef(lm(formula = y ~ x, data = as.data.frame(m)))[2]
       }, by = 3, by.column = FALSE
   )
}
do.call("rbind", by(dat, dat[c("w", "z")], rolled))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!