首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >xts::period.apply和cumprod

xts::period.apply和cumprod
EN

Stack Overflow用户
提问于 2012-11-01 06:47:41
回答 1查看 1.6K关注 0票数 7

我正在尝试计算xts对象子集的累积乘积。这是我想要的一个例子,还有一个问题是,使用period.apply或其他基于c++的快速函数是否可以更快/更优雅地实现这一点?

代码语言:javascript
复制
# 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?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-01 07:07:30

period.apply和朋友不会工作,因为他们每个周期只返回一个观察值。你想要更像ave的东西

代码语言:javascript
复制
dep <- diff(ep)
out.ave <- ave(test+1, rep(ep, c(0,dep)), FUN=cumprod)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13168545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档