有沒有辦法在傳遞rowSums
a xts
對象時保留xts
對象的索引?當在xts上使用rowSums時保留xts索引
目前我將結果重寫爲xts
對象,但這看起來沒有像rowSums
能夠簡單地返回它傳遞的結果那樣快。
xts(rowSums(abs(data)),index(data))
有沒有辦法在傳遞rowSums
a xts
對象時保留xts
對象的索引?當在xts上使用rowSums時保留xts索引
目前我將結果重寫爲xts
對象,但這看起來沒有像rowSums
能夠簡單地返回它傳遞的結果那樣快。
xts(rowSums(abs(data)),index(data))
有趣的問題。讓我們忽略abs
的計算,因爲與價格相關的時間並不相關。如果您關注的是性能,這裏是一組定時考慮當前建議:
library(microbenchmark)
sample.xts <- xts(order.by = as.POSIXct("2004-01-01 00:00:00") + 1:1e6, matrix(rnorm(1e6 *4), ncol = 4), dimnames = list(NULL, c("A", "B", "C", "D")))
# See how quickly rowSum works on just the underlying matrix of data in the timings below:
xx <- coredata(sample.xts)
microbenchmark(
coredata(sample.xts),
rowSums(xx),
rowSums(sample.xts),
rowSums(coredata(sample.xts)),
.xts(x = rowSums(sample.xts), .index(sample.xts)),
xts(rowSums(coredata(sample.xts)), index(sample.xts)),
xts(rowSums(sample.xts),index(sample.xts)),
Reduce("+", as.list(sample.xts)), times = 100)
# Unit: milliseconds
# expr min lq mean median uq max neval
# coredata(sample.xts) 2.558479 2.661242 6.884048 2.817607 6.356423 104.57993 100
# rowSums(xx) 10.314719 10.824184 11.872108 11.289788 12.382614 18.39334 100
# rowSums(sample.xts) 10.358009 10.887609 11.814267 11.335977 12.387085 17.16193 100
# rowSums(coredata(sample.xts)) 12.916714 13.839761 18.968731 15.950048 17.836838 113.78552 100
# .xts(x = rowSums(sample.xts), .index(sample.xts)) 14.402382 15.764736 20.307027 17.808984 19.072600 114.24039 100
# xts(rowSums(coredata(sample.xts)), index(sample.xts)) 20.490542 24.183286 34.251031 25.566188 27.900599 125.93967 100
# xts(rowSums(sample.xts), index(sample.xts)) 17.436137 19.087269 25.259143 21.923877 22.805013 119.60638 100
# Reduce("+", as.list(sample.xts)) 21.745574 26.075326 41.696152 27.669601 30.442397 136.38650 100
y = .xts(x = rowSums(sample.xts), .index(sample.xts))
y2 = xts(rowSums(sample.xts),index(sample.xts))
all.equal(y, y2)
#[1] TRUE
coredata(sample.xts)
返回底層數字矩陣。我認爲您可以預期的最快性能是rowSums(xx)
用於計算,這可以被認爲是「基準」。問題是,在xts
對象中,最快的方法是什麼?看起來 .xts(x = rowSums(sample.xts), .index(sample.xts))
給人體面的表現。
如果你的異議是有挑開,並放在一起輸入的成分那麼如果x
是您的XTS對象,然後嘗試。它直接返回一個xts對象:
Reduce("+", as.list(x))
感謝您的回覆。我主要關心的是整潔,因爲調用已經存在於lapply lambda函數中。 – theGreatKatzul
感謝Josh的快速和周到的答覆。 – theGreatKatzul
@theGreatKatzul:這是FXQuantTrader的回覆。我唯一的貢獻是對齊microbenchmark輸出中的標題。 –
恩,那麼謝謝FXQuantTrader! – theGreatKatzul