I have a monthly data for each group, and I want to do regression for each group, and window is 2 years and get slope.
I tried several methods
- I tried to use for loop and filter 2-year data each time, then do lm
df$Year =year(df$date) df1<-purrr::map_df(min(df$Year):(max(df$Year) - 2), function(i) { df %>% filter(Year%in% c(i,i+1)) %>% group_by(group)%>% do(lm = lm(R ~ M, data = .,na.action=na.exclude)) %>% mutate(lm_b0 = summary(lm)$coeff[1], lm_b1 = summary(lm)$coeff[2])%>% ungroup() })
get the error:
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases
- then I tried to define a function slope, but result df1, column "slope" is all NA
slope <- . %>% { cov(.[, 2], .[, 1]) / var(.[, 2])} df1<-df %>% group_by(group,Year) %>% mutate(slope = rollapplyr(cbind(R, M), 2, slope, by.column = FALSE, fill = NA)) %>%ungroup()
- and I found roll_lm method:
library(roll) df1<-df%>% group_by(group,Year)%>% roll_lm(MKT,RET,2)
get the error:
Error in roll_lm(., M, R, 5) : object 'M' not found
4.The I tried this, but result is all NA
df1<-df%>%
group_by(group,Year)%>%
do(data.frame(., rolling_coef = rollapplyr(data = ., width = 2, FUN = function(df_) {
mod = lm(R ~ M, data = .)
return(coef(mod)[2])
}, by.column = FALSE, fill = NA)))
I also tried use beta
directly, it could work, but seems beta is for nonnegative numeric variable, my M and R have negative value.
Could someone give me some ideas? Thank you!
My dataset is similar to this:
and I want the result be: (2002: use previous two-year monthly data do regression and find slope)