2017-03-02 58 views
2

我與一些數據樣本XTS對象:與交易應用XTS對象的功能中的R

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) 

然後我就可以使用apply.yearly與功能cumsum:

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

問題與使用應用的是,它返回一個矩陣,而不是一個XTS對象。雖然我可以通過使用as.xts來解決這個問題,但我想知道是否有某些我錯過了,或者如果我正在使用apply.yearly不正確。使用純粹的應用程序似乎更容易發現錯誤和錯誤。

+0

'apply'總是返回'matrix'無論您是使用' xts'或'data.frame' – akrun

+0

只需使用'reclass()'使它再次成爲'xts':'reclass(apply(X = xts_object,MARGIN = 2,FUN = cumsum),match.to = xts_object)' – Rime

+0

您的'apply'調用的輸出不會重置每年的累計和。這與調用'cumsum(xts_object)'相同。 'apply.yearly'也應該重置每年的累計金額。 –

回答

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" 

最終的目標仍然是「XTS」

+0

很好的答案。這就是'apply.yearly'應該做的。它看起來不像一個bug。我將不得不考慮'period.apply'目前如何工作以便修補。 –

+0

useR這就是我最初的想法,我編輯了我原來的帖子,以反映你的回答。正如約書亞評論說,這是適用的。每年應該做的,所以我想我真的沒有使用apply.yearly錯誤,它需要一個補丁。謝謝你們兩位! – Rafolks