7

xtsオブジェクトのサブセットの累積積を計算しようとしています。これが私が欲しいものの例であり、これがperiod.applyまたは他のc++ベースの高速関数を使用してより速く/よりエレガントに実行できるかどうかという質問です。

# install.packages("qmao", repos="http://R-Forge.R-project.org")
require(qmao) # for do.call.rbind()

# I need something like cumprod over xts but by endpoints (subsets of xts)
test <- xts(rep(0.01, length(as.Date(13514:13523, origin="1970-01-01"))), as.Date(13514:13523, origin="1970-01-01"))
ep <- c(0, 5, NROW(test))
# This does not do the trick
period.prod(test, INDEX=ep)
# So, try the obvious, but it does not do the trick
period.apply(test, INDEX=ep, FUN=function(x) cumprod(1 + x))

# Well, write your own
# Hm, there is no split.xts that takes ep (endpoints) as parameter...
# OK, split it manually
test.list <- list(length(ep) - 1)
k <- 1:(length(ep) - 1)
test.list <- lapply(k, function(x) test[(ep[x] + 1):ep[x + 1], ])
# This is what I want...
do.call.rbind(lapply(test.list, function(x) cumprod(1 + x)))
# Is there a better/faster way to do this?
4

1 に答える 1

5

period.applyと友人は、期間ごとに1つの観測値しか返さないため、機能しません。あなたはもっと次のようなものが欲しいですave

dep <- diff(ep)
out.ave <- ave(test+1, rep(ep, c(0,dep)), FUN=cumprod)
于 2012-10-31T23:07:29.950 に答える