简体   繁体   中英

Apply a rolling function to a data.table in R with a custom window size

I want to apply a rolling min function to a data table but with a custom start and end point for the window.

In this data set column x is what I want the min to be applied to and y is the desired output.

library(data.table) #version 1.13.6
dt <- data.table(x = seq(1:50))
dt[, y := c(0,0,0,0,0,0,0,0,0, seq(1:41))]

In my current data I want to get the rolling min value over a window of 5 centered to the right, but I want it to start from 5 rows before the current row. So in row 10, it is looking for the min in rows 1:5, in row 11 it is looking at rows 2:6 and so on. Thanks

dt[, z := shift(frollapply(x, n = 5, FUN = min, fill = 0), n = 5, fill = 0)]
dt[, all.equal(y, z)] # TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM