假设我想对返回大于值的函数使用rollapply。如下所示:
library(quantmod)
getSymbols("YHOO")
openYHOO <- YHOO[1:10,1]
rollapply(openYHOO, width = 2, range)我犯了个错误。我还尝试将函数中的结果合并:
rollapply(openYHOO, width = 2, function(x) {
cbind(range(x))
})
rollapply(openYHOO, width = 2, function(x) {
merge(range(x))
})更多的错误。
我可以这么做:
cbind(
rollapply(openYHOO, width = 2, function(x) {
range(x)[1]
}),
rollapply(openYHOO, width = 2, function(x) {
range(x)[2]
})
)...and它起作用了。
但是,如果我想调用fivenum或者在有趣的争论中使用更复杂和计算更密集的东西,该怎么办?是否必须对要返回的每个值调用rollapply,并一次又一次地生成相同的对象?
我是遗漏了什么,还是应该放弃rollapply并滚动自己的滚动窗口功能?
您能解释一下为什么这个rollapply(openYHOO, width = 2, range)不能工作吗?
发布于 2015-08-21 02:29:39
使用by.column参数
rollapply(openYHOO, width=2, range, by.column=FALSE)
# [,1] [,2]
#2007-01-03 NA NA
#2007-01-04 25.64 25.85
#2007-01-05 25.64 26.70
#2007-01-08 26.70 27.70
#2007-01-09 27.70 28.00
#2007-01-10 27.48 28.00
#2007-01-11 27.48 28.76
#2007-01-12 28.76 28.98
#2007-01-16 28.98 29.88
#2007-01-17 29.40 29.88
> rollapply(openYHOO, width=2,
function(x) fivenum(as.numeric(x)),
by.column=FALSE)
# [,1] [,2] [,3] [,4] [,5]
#2007-01-03 NA NA NA NA NA
#2007-01-04 25.64 25.64 25.745 25.85 25.85
#2007-01-05 25.64 25.64 26.170 26.70 26.70
#2007-01-08 26.70 26.70 27.200 27.70 27.70
#2007-01-09 27.70 27.70 27.850 28.00 28.00
#2007-01-10 27.48 27.48 27.740 28.00 28.00
#2007-01-11 27.48 27.48 28.120 28.76 28.76
#2007-01-12 28.76 28.76 28.870 28.98 28.98
#2007-01-16 28.98 28.98 29.430 29.88 29.88
#2007-01-17 29.40 29.40 29.640 29.88 29.88https://stackoverflow.com/questions/32131399
复制相似问题