xts中的cumsum表示已经汇总但每年重置的值

时间:2017-04-20 16:59:01

标签: r dataframe xts

数据:

        [,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,但它返回了运行总计,并且多年来都没有变化。

1 个答案:

答案 0 :(得分:0)

现在我理解了你的问题,这是一个解决方案。这些评论有希望解释正在做什么。

# 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)