本文介绍了R:滚动日期范围内的累积总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,如何计算要在计算行之前的定义时间段内的总和?

In R, how can I calculate cumsum for a defined time period prior to the row being calculate? Prefer dplyr if possible.

例如,如果期限为10天,则该函数将达到cum_rolling10:

For example, if the period was 10 days, then the function would achieve cum_rolling10:

date    value   cumsum  cum_rolling10
1/01/2000   9   9       9
2/01/2000   1   10      10
5/01/2000   9   19      19
6/01/2000   3   22      22
7/01/2000   4   26      26
8/01/2000   3   29      29
13/01/2000  10  39      29
14/01/2000  9   48      38
18/01/2000  2   50      21
19/01/2000  9   59      30
21/01/2000  8   67      38
25/01/2000  5   72      24
26/01/2000  1   73      25
30/01/2000  6   79      20
31/01/2000  6   85      18


推荐答案

使用 dplyr , tidyr lubridate zoo

library(dplyr)
library(tidyr)
library(lubridate)
library(zoo)

dt2 <- dt %>%
  mutate(date = dmy(date)) %>%
  mutate(cumsum = cumsum(value)) %>%
  complete(date = full_seq(date, period = 1), fill = list(value = 0)) %>%
  mutate(cum_rolling10 = rollapplyr(value, width = 10, FUN = sum, partial = TRUE)) %>%
  drop_na(cumsum)
dt2
# A tibble: 15 x 4
         date value cumsum cum_rolling10
       <date> <dbl>  <int>         <dbl>
 1 2000-01-01     9      9             9
 2 2000-01-02     1     10            10
 3 2000-01-05     9     19            19
 4 2000-01-06     3     22            22
 5 2000-01-07     4     26            26
 6 2000-01-08     3     29            29
 7 2000-01-13    10     39            29
 8 2000-01-14     9     48            38
 9 2000-01-18     2     50            21
10 2000-01-19     9     59            30
11 2000-01-21     8     67            38
12 2000-01-25     5     72            24
13 2000-01-26     1     73            25
14 2000-01-30     6     79            20
15 2000-01-31     6     85            18

数据

dt <- structure(list(date = c("1/01/2000", "2/01/2000", "5/01/2000", 
"6/01/2000", "7/01/2000", "8/01/2000", "13/01/2000", "14/01/2000", 
"18/01/2000", "19/01/2000", "21/01/2000", "25/01/2000", "26/01/2000", 
"30/01/2000", "31/01/2000"), value = c(9L, 1L, 9L, 3L, 4L, 3L, 
10L, 9L, 2L, 9L, 8L, 5L, 1L, 6L, 6L)), .Names = c("date", "value"
), row.names = c(NA, -15L), class = "data.frame")

这篇关于R:滚动日期范围内的累积总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 00:05