xtszoorollapply

how to build multiple sliding windows from xts object using rollapply function


I have a matrix with two columns where each column is a variable. I'm building two sliding windows of size 3

data <- matrix(1:20,ncol = 2, dimnames = list(NULL, c("var1","var2")))
> data
      var1 var2
 [1,]    1   11
 [2,]    2   12
 [3,]    3   13
 [4,]    4   14
 [5,]    5   15
 [6,]    6   16
 [7,]    7   17
 [8,]    8   18
 [9,]    9   19
[10,]   10   20

> rollapplyr(data, 3, c)

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3   11   12   13
[2,]    2    3    4   12   13   14
[3,]    3    4    5   13   14   15
[4,]    4    5    6   14   15   16
[5,]    5    6    7   15   16   17
[6,]    6    7    8   16   17   18
[7,]    7    8    9   17   18   19
[8,]    8    9   10   18   19   20

But when I try to do the same with the xtc object I get an error

library(xts)
 data_xts <- xts(data, Sys.time()+1:10)
 rollapplyr(data_xts, 3, c)

Error in array(ans, c(len.a%/%d2, d.ans), if (!is.null(names(dn.ans)) ||  : 
  length of 'dimnames' [1] not equal to array extent

Solution

  • rollapplyr(zoo(data_xts), 3, c)
    

    Yields the expected behaviour based on your example.