处理R中xts对象的apply函数

拉福克人

我有一些数据的样本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的问题是它返回一个矩阵而不是一个xts对象。虽然可以使用as.xts解决此问题,但我想知道是否缺少某些内容,或者我是否错误地使用了apply.yearly。使用纯应用似乎更容易捕获错误和错误。

avid_useR

这可能不是最优雅的解决方案,但它可以起作用:

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

结果对象仍然是“ xts”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章