cumsum() 直到并包括 dplyr 中的当前日期

cumsum() up to and including current date in dplyr

我想计算当前日期之前(包括当前日期)所有日期的累计值。问题是我在同一日期有多个条目,所以如果我使用 cumsum,我会为同一日期发生的值得到不同的值:

library(dplyr)
tribble(~date, ~value,
        "2017-01-01", 1,
        "2017-01-02", 2,
        "2017-01-02", 3,
        "2017-01-03", 4,
        "2017-01-03", 5,
        "2017-01-04", 6,
        "2017-01-09", 9) %>% 
  arrange(date) %>% 
  mutate(to_date=cumsum(value))
>
# A tibble: 7 x 3
        date value  to_date
       <chr> <dbl>    <dbl>
1 2017-01-01     1        1
2 2017-01-02     2        3
3 2017-01-02     3        6
4 2017-01-03     4       10
5 2017-01-03     5       15
6 2017-01-04     6       21
7 2017-01-09     9       30

是否有一种优雅的方法可以得到以下输出:

# A tibble: 7 x 3
        date value  to_date
       <chr> <dbl>    <dbl>
1 2017-01-01     1        1
2 2017-01-02     2        6
3 2017-01-02     3        6
4 2017-01-03     4       15
5 2017-01-03     5       15
6 2017-01-04     6       21
7 2017-01-09     9       30

出于各种原因(除其他外,我的 table 中有更多字段)我无法按 运行 累计总数之前的数据进行汇总。我(可能)需要一个不断增长的 window 函数来计算时间间隔的总数。

我们可以group_by'date'然后得到last'to_date'

df1 %>%
    group_by(date) %>%
    mutate(to_date = last(to_date))

或者,可以在旁边按日期汇总值,计算 cumsum 并在最后将结果加入原始数据。

library(dplyr)
df<-tribble(~date, ~value,
        "2017-01-01", 1,
        "2017-01-02", 2,
        "2017-01-02", 3,
        "2017-01-03", 4,
        "2017-01-03", 5,
        "2017-01-04", 6,
        "2017-01-09", 9) 

df %>% group_by(date) %>% 
  summarize(to_date=sum(value)) %>% 
  arrange(date) %>% 
  mutate(to_date=cumsum(to_date)) %>% 
  right_join(df, by=c("date"))

结果是:

# A tibble: 7 x 3
        date to_date value
       <chr>   <dbl> <dbl>
1 2017-01-01       1     1
2 2017-01-02       6     2
3 2017-01-02       6     3
4 2017-01-03      15     4
5 2017-01-03      15     5
6 2017-01-04      21     6
7 2017-01-09      30     9