alignment and offsets in rollapply

不打扰是莪最后的温柔 提交于 2020-01-03 13:10:28

问题


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.


回答1:


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

     width=list(-1:-5) 

accomplishes it.




回答2:


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)


来源:https://stackoverflow.com/questions/32234585/alignment-and-offsets-in-rollapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!