xts 中的 cumsum 用于已经求和但每年重置的值

cumsum in an xts for values that already sum but reset every year

数据:

        [,1]
2015-03-17 1
2015-03-18 2
2015-03-19 4
{cont}
2015-12-31 200
2016-01-01 0
2016-12-02 3
2016-12-03 9

因为这个 xts 已经有 运行 年内的总数,我想计算跨年的 运行 总数。

看起来像

           Value   ## cumsum(value) ## not what I want
2015-03-17 1        # 1
2015-03-18 2        # 3
2015-03-19 4        # 7
{cont}              # {cont}
2015-12-31 200      # x, where x is much bigger than 200
2016-01-01 200      # x + x
2016-01-02 203      # 3x + 3
2016-12-03 209      # 4x + 3 + 9

我尝试使用 cumsummutate,但它返回的总数是 运行,并且多年没有改变。

现在我明白了你的问题,这里有一个解决方案。希望评论能解释正在做的事情。

# Merge original data with year-end values, filling with zeros
y <- merge(x, year.end = apply.yearly(x, last), fill = 0)

# Lag year-end values, so they appear at the start of the following year
y$year.end <- lag(y$year.end)

# Set first NA to zero (so cumsum results aren't all NA)
y$year.end[1] <- 0

# Take a cumulative sum of the year-end values, so they increase each year
y$year.end <- cumsum(y$year.end)

# Add two columns to create running total
y$running.total <- rowSums(y)