This is related to rolling regression by group in the tidyverse?
Consider again this simple example
library(dplyr)
library(purrr)
library(broom)
library(zoo)
library(lubridate)
mydata = data_frame('group' = c('a','a', 'a','a','b', 'b', 'b', 'b'),
'y' = c(1,2,3,4,2,3,4,5),
'x' = c(2,4,6,8,6,9,12,15),
'date' = c(ymd('2016-06-01', '2016-06-02', '2016-06-03', '2016-06-04',
'2016-06-03', '2016-06-04', '2016-06-05','2016-06-06')))
group y x date
<chr> <dbl> <dbl> <date>
1 a 1.00 2.00 2016-06-01
2 a 2.00 4.00 2016-06-02
3 a 3.00 6.00 2016-06-03
4 a 4.00 8.00 2016-06-04
5 b 2.00 6.00 2016-06-03
6 b 3.00 9.00 2016-06-04
7 b 4.00 12.0 2016-06-05
8 b 5.00 15.0 2016-06-06
What I am trying to do here is pretty simple.
For each group (in this example, a or b):
- compute the rolling regression of y on x over the last 2 observations.
- store the coefficient of that rolling regression AND its confidence interval in a column of the dataframe.
I tried to modify the existing solution above, but adding the confidence interval proves to be difficult, so this works (without the confidence interval):
Coef <- . %>% as.data.frame %>% lm %>% coef
mydata %>%
group_by(group) %>%
do(cbind(reg_col = select(., y, x) %>% rollapplyr(2, Coef, by.column = FALSE, fill = NA),
date_col = select(., date))) %>%
ungroup
# A tibble: 8 x 4
group `reg_col.(Intercept)` reg_col.x date
<chr> <dbl> <dbl> <date>
1 a NA NA 2016-06-01
2 a 0 0.5 2016-06-02
3 a 0 0.5 2016-06-03
4 a 0 0.5 2016-06-04
5 b NA NA 2016-06-03
6 b 0.00000000000000126 0.333 2016-06-04
7 b -0.00000000000000251 0.333 2016-06-05
8 b 0 0.333 2016-06-06
However, THIS does not work (WITH the confidence interval) :-(
Coef <- . %>% as.data.frame %>% lm %>% tidy(., conf.int = TRUE) %>% as_tibble()
> mydata %>%
+ group_by(group) %>%
+ do(reg_col = select(., y, x) %>% rollapplyr(2, Coef, by.column = FALSE, fill = NA)) %>%
+ ungroup()
# A tibble: 2 x 2
group reg_col
* <chr> <list>
1 a <dbl [4 x 2]>
2 b <dbl [4 x 2]>
With this list-column
being super weird. Any ideas what is missing here?
Thanks!!