alignment and offsets in rollapply
Asked Answered
T

2

5

I am trying to calculate some statistics for a moving window and am using rollapply in the zoo package. My question is how do I get rollapply to apply that function to the previous n observations instead of the current observation and the previous n-1 observations as align right seems to do.

require(zoo)
z <- data.frame(x1=11:111, x2=111:211, x3=as.Date(31:131))#generate data
output<-data.frame(dates=z$x3,
                   rollapply(z[,1:2],by.column=TRUE, 5, max, fill=NA, align='right'))

I have a hunch this is answered by ?rollapply "If width is a plain numeric vector its elements are regarded as widths to be interpreted in conjunction with align whereas if width is a list its components are regarded as offsets. In the above cases if the length of width is 1 then width is recycled for every by-th point. If width is a list its components represent integer offsets such that the i-th component of the list refers to time points at positions i + width[[i]]." But I have no idea what that means in terms of R code an no example is provided.

Trifocal answered 26/8, 2015 at 18:56 Comment(1)
No examples??? In zoo 1.7-12 which was the current version at the time of this question there were 19 examples of using offsets with rollapply on the ?rollapply page.Noella
T
6

Nevermind, I deciphered the 'help.' Adding the parameter width to rollapply like this:

     width=list(-1:-5) 

accomplishes it.

Trifocal answered 26/8, 2015 at 19:23 Comment(0)
E
1

If I'm reading correctly, you just want the column "shifted" down by one - so that the value for row n is the value that row n+1 has now.

This can be easily done using the lag function:

z <- data.frame(x1=11:111, x2=111:211, x3=as.Date(31:131))#generate data
output<-data.frame(dates=z$x3,
                   rollapply(z[,1:2],by.column=TRUE, 5, max, fill=NA, align='right'))
output$x1 <- lag(output$x1, 1)
output$x2 <- lag(output$x2, 1)
Erective answered 26/8, 2015 at 19:15 Comment(1)
thanks, but i figure out how to make it do what I wanted.Trifocal

© 2022 - 2024 — McMap. All rights reserved.