r - Rolling regression with dplyr and lsfit -
i'm trying run rolling regression dplyr
. i'm using rollapplyr
package zoo
, lsfit
i'm interested in beta of regression. here's i've tried:
library(dplyr); library(zoo) df1 = expand.grid(site = seq(10), year = 2000:2004, day = 1:50) df1 %>% group_by(year) %>% mutate(beta1 = rollapplyr(data = site, width = 5, fun = lsfit, x=day))
i'm getting error: error: not arguments have same length
i think rollapplyr
accepts non-zoo objects may wrong. piping (%>%
) not play rollapplyr
requires data object in function.
any idea?
edit question different from: rolling regression dplyr want use pipes in order use group_by
the function not cycle through multiple vectors. sliced site
vector being compared full vector day
. can write our own rolling apply function map
go through groups of our vector:
rollapplydf <- function(xx, width) { l <- length(xx) sq <- map(':', 1:(l-width+1), width:l) lst <- lapply(sq, function(i) lm(xx[i] ~ seq(length(xx[i])))$coeff[2] ) do.call('rbind', c(rep(na, width-1l), lst)) }
so can add pipe:
library(dplyr) df1 %>% group_by(year) %>% mutate(beta1 = rollapplydf(xx = site, width = 5) ) # source: local data frame [2,500 x 4] # groups: year [5] # # site year day beta1 # (int) (int) (int) (dbl) # 1 1 2000 1 na # 2 2 2000 1 na # 3 3 2000 1 na # 4 4 2000 1 na # 5 5 2000 1 1 # 6 6 2000 1 1 # 7 7 2000 1 1 # 8 8 2000 1 1 # 9 9 2000 1 1 # 10 10 2000 1 1 # .. ... ... ... ...