I am trying to calculate cumulative product for subsets of xts object. Here is an example of what I want and a question whether this can be done faster/more elegant using period.apply or some other c++ based fast function?
# 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?
period.apply
and friends won't work because they only return one observation per period. You want something more like ave
:
dep <- diff(ep)
out.ave <- ave(test+1, rep(ep, c(0,dep)), FUN=cumprod)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With