Search code examples
rrollapply

rollapply with function that returns more than one value


Say I want to use rollapply with a function that returns more than on value. Like this:

library(quantmod)
getSymbols("YHOO")

openYHOO <- YHOO[1:10,1]

rollapply(openYHOO, width = 2, range)

I get an error. I also tried merging the results inside the function:

rollapply(openYHOO, width = 2, function(x) {
  cbind(range(x))
})

rollapply(openYHOO, width = 2, function(x) {
  merge(range(x))
})

More errors.
I can do this:

cbind(
  rollapply(openYHOO, width = 2, function(x) {
    range(x)[1]
  }),
  rollapply(openYHOO, width = 2, function(x) {
    range(x)[2]
  })
)

...and it works.

However, what if I want to call fivenum or use something much more complicated and computationally intensive in the fun argument? Do I have to call rollapply for each value that I want to return, generating the same object over and over again?

Am I missing something or should I abandon rollapply and roll my own rolling window function?

Can you explain why this rollapply(openYHOO, width = 2, range) does not work?


Solution

  • Use the by.column argument

    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.88