Dplyr 在汇总分组数据上滞后

Dplyr Lags on Summarised Grouped Data

使用 dplyr,我希望将新的数据列汇总为 grouped 数据的现有列的​​滞后版本。

代表:

    dateidx <- as.Date(c("2019-01-02", "2019-01-032", "2019-01-02", "2019-01-07", "2019-01-07", "2019-01-07", "2019-01-10", "2019-01-10"))
    A <- c(100, 100, 200, 200, 200, 300, 400, 135)
    B <- c(1500, 2000, 1350, 780, 45, 200, 150, 250)
    test.df1 <- data.frame(dateidx, A, B)

> test.df1
     dateidx   A    B
1 2019-01-02 100 1500
2 2019-01-03 100 2000
3 2019-01-02 200 1350
4 2019-01-07 200  780
5 2019-01-07 200   45
6 2019-01-07 300  200
7 2019-01-10 400  150
8 2019-01-10 135  250

Objective:

>dateidx <- c("2019-01-02","2019-01-03", "2019-01-07", "2019-01-10")
> sumA <- c(300, 100, 700, 535)
> sumAlag <- c(NA, 300, 100, 700)
> meanB <- c(1425, 2000, 342, 200)
> meanBlag <- c(NA, 1425, 2000, 342)
> test.obj <- data.frame (dateidx2, sumA, sumAlag, meanB, meanBlag)

> test.obj

    dateidx sumA sumAlag meanB meanBlag
1 2019-01-02  300      NA  1425       NA
2 2019-01-03  100     300  2000     1425
3 2019-01-07  700     100   342     2000
4 2019-01-10  535     700   200      342

我的代码:

test.df2 <- test.df1 %>%
  group_by(dateidx) %>%
  summarise (
    sumA = sum(A), 
    sumAlag = lag(sumA),
    meanB = mean(B), 
    meanBlag =dplyr::lag(meanB)
  )

期望的结果:

    dateidx sumA sumAlag meanB meanBlag
1 2019-01-02  300      NA  1425       NA
2 2019-01-03  100     300  2000     1425
3 2019-01-07  700     100   342     2000
4 2019-01-10  535     700   200      342

实际结果:

> test.df2
# A tibble: 4 × 5
  dateidx     sumA sumAlag meanB meanBlag
  <date>     <dbl>   <dbl> <dbl>    <dbl>
1 2019-01-02   300      NA 1425        NA
2 2019-01-03   100      NA 2000        NA
3 2019-01-07   700      NA  342.       NA
4 2019-01-10   535      NA  200        NA

尝试修复:

消除歧义(比如 dplyr / plyr:: mutate 问题)

创建虚拟变量

使用“order-by”重新指定分组

几年前修复的 dplyr 错误

来源:

https://dplyr.tidyverse.org/reference/lead-lag.html: 但没有讨论分组

https://dplyr.tidyverse.org/reference/lead-lag.html:仅在第一粒度上超前或滞后

:关于确保消除延迟:其他不相关的问题

Lag function on grouped data: 对于 python

:明显滞后 组内

你想先summarise得到总和和平均值,然后你可以用一个mutate语句得到每列的滞后,然后重新排列列。

library(tidyverse)

test.df2 <- test.df1 %>%
  group_by(dateidx) %>%
  summarise(sumA = sum(A),
            meanB = mean(B)) %>%
  mutate(sumAlag = lag(sumA),
         meanBlag = lag(meanB)) %>% 
  select(dateidx, starts_with("sum"), starts_with("mean"))

输出

  dateidx     sumA sumAlag meanB meanBlag
  <date>     <dbl>   <dbl> <dbl>    <dbl>
1 2019-01-02   300      NA 1425       NA 
2 2019-01-03   100     300 2000     1425 
3 2019-01-07   700     100  342.    2000 
4 2019-01-10   535     700  200      342.