处理R中xts对象的应用函数

时间:2017-03-02 02:21:31

标签: r time-series apply xts cumsum

我有一个带有一些数据的示例xts对象:

dates <- seq.Date(from = as.Date("2010-01-01", format = "%Y-%m-%d"), 
to = as.Date("2013-12-01", format = "%Y-%m-%d"), by = "month")

sample_data <- cbind(1:length(dates),length(dates):1)

xts_object <- xts(x = sample_data, order.by = dates)

然后我使用函数cumsum:

使用apply.yearly
apply.yearly(x = xts_object, FUN = cumsum)

输出是一个转置矩阵,这不是我原本打算返回的。

我希望上面的代码段能够返回相同的输出:

rbind(apply(X = xts_object[1:12],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[13:24],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[25:36],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[37:48],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[49:60],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[61:72],MARGIN = 2,FUN = cumsum),
apply(X = xts_object[73:84],MARGIN = 2,FUN = cumsum))

使用apply的问题是它返回一个矩阵而不是一个xts对象。虽然我可以通过使用as.xts来解决这个问题,但我想知道是否有遗漏的东西,或者我是否正在使用apply.yearly错误。使用纯apply似乎更容易捕获错误和错误。

1 个答案:

答案 0 :(得分:2)

这可能不是最优雅的解决方案,但它有效:

# Split xts_object by year
xts_list = split(xts_object, "years")
# cumsum for each year
cumsum_list = lapply(xts_list, FUN = cumsum)
# rbind them together
do.call(rbind, cumsum_list)  

#             [,1] [,2]
# 2010-01-01    1   48
# 2010-02-01    3   95
# 2010-03-01    6  141
# 2010-04-01   10  186
# 2010-05-01   15  230
# 2010-06-01   21  273
# 2010-07-01   28  315
# 2010-08-01   36  356
# 2010-09-01   45  396
# 2010-10-01   55  435
# 2010-11-01   66  473
# 2010-12-01   78  510
# 2011-01-01   13   36
# 2011-02-01   27   71
# 2011-03-01   42  105
# 2011-04-01   58  138
# 2011-05-01   75  170
# 2011-06-01   93  201
# 2011-07-01  112  231
# 2011-08-01  132  260
# 2011-09-01  153  288
# 2011-10-01  175  315
# 2011-11-01  198  341
# 2011-12-01  222  366
# 2012-01-01   25   24
# 2012-02-01   51   47
# 2012-03-01   78   69
# 2012-04-01  106   90
# 2012-05-01  135  110
# 2012-06-01  165  129
# 2012-07-01  196  147
# 2012-08-01  228  164
# 2012-09-01  261  180
# 2012-10-01  295  195
# 2012-11-01  330  209
# 2012-12-01  366  222
# 2013-01-01   37   12
# 2013-02-01   75   23
# 2013-03-01  114   33
# 2013-04-01  154   42
# 2013-05-01  195   50
# 2013-06-01  237   57
# 2013-07-01  280   63
# 2013-08-01  324   68
# 2013-09-01  369   72
# 2013-10-01  415   75
# 2013-11-01  462   77
# 2013-12-01  510   78

class(do.call(rbind, cumsum_list))
# [1] "xts" "zoo"

结果对象仍然是&#34; xts&#34;