2017-04-20 33 views
1

数据值:cumsum在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,但它返回的运行总量,多年来没有改变。

+0

我不明白你的问题。您的数据在每个日历年开始时的运行总数为零。你想要在整个时间段内运行的总和,这就是'cumsum(x)'所做的。但是你说这是行不通的,因为“它返回了跑步总数并且多年没有变化”,这听起来像你所说的你想要的。 –

+0

也许我正在使用'cumsum'错误,但它保持了运行总数,因为我只希望2015年的总额(在12/31提供的值)在2016年的每个值中都加上 –

+0

啊,我想我明白了。例如,你希望'c(0:5,0:5)'变成'c(0:5,0:5 + 5)'。 –

回答

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)