【发布时间】:2018-08-08 18:13:09
【问题描述】:
这与rolling regression by group in the tidyverse?有关
再次考虑这个简单的例子
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
我在这里要做的很简单。
对于每个组(在本例中为 a 或 b):
- 在最后 2 次观察中计算 y 在 x 上的滚动回归。
- 将该滚动回归的系数及其置信区间存储在数据框的一列中。
我尝试修改上面现有的解决方案,但添加置信区间被证明是困难的,所以这可行(没有置信区间):
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
但是,THIS 不起作用(有置信区间):-(
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]>
这个list-column 非常奇怪。任何想法这里缺少什么?
谢谢!!
【问题讨论】:
-
Coef函数应该返回一个向量,而不是数据框或 tibble。 -
嗨,格洛腾迪克,你来了!感谢您的参与。是的,但我也需要使用这些
tidy友好的软件包。我正在尝试类似Coef <- . %>% as.data.frame %>% lm %>% tidy(., conf.int = TRUE) %>% as_tibble() %>% filter(term == 'surp') -
@G.Grothendieck 我在下面尝试了一些方法。请你看看,看看你是否可以改进?我当然很乐意接受你的提议!谢谢!
-
@G.Grothendieck 我不明白为什么我的输出中有这些烦人的引号......