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和朋友不会工作,因为他们每个时期只返回一个观察结果。你想要更多的东西ave

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