我正在尝试使用rollapply,因此我只使用一次,而不是多次,然后合并结果。想法是我想从xts
对象获取多个数据位。在下面的模拟示例中,我希望能够获得滑动窗口的总和和最大值。
require(xts)
v <- xts(rnorm(100),Sys.Date()-100:1)
rollapply(v,width=10,function(y){c(sum(y),max(y))})
这会导致以下错误......
Error in xts(xx, tt, if (by == 1) attr(data, "frequency")) :
NROW(x) must match length(order.by)
以下是我正在运行的sessionInfo:
R version 2.15.2 (2012-10-26)
Platform: i386-apple-darwin9.8.0/i386 (32-bit)
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] xts_0.9-3 zoo_1.7-9
loaded via a namespace (and not attached):
[1] grid_2.15.2 lattice_0.20-10
我以为我已经想到了这个,但显然不是......
答案 0 :(得分:3)
当输入只有一列时,这是当前实现的限制。您可以通过确保输入包含多个列,设置by.column=FALSE
,并使您的函数仅使用一列来解决此问题。
例如:
require(xts)
v <- xts(rnorm(10),Sys.Date()-10:1)
f <- function(y) c(sum=sum(y[,1]), max=max(y[,1]))
rollapply(merge(v,v), width=3, f, by.column=FALSE)
答案 1 :(得分:0)
这是你可以做到的一种方式......
sapply( c("sum" , "max" ) , function(x) rollapply( v , width = 10 , FUN = eval(x) , align = "left" ) )
# sum max
# [1,] -2.43662744 1.6931489
# [2,] -1.95346657 1.6931489
# [3,] -0.66191032 1.6931489
# [4,] -1.97506474 1.6931489
# [5,] -3.12090491 1.6931489
# [6,] -6.32315512 0.6908325
# [7,] -3.09130768 2.4151086
# [8,] -1.27864497 2.4151086
# [9,] -0.20942059 2.4151086
# [10,] -0.39156830 2.4151086