Last active
October 2, 2023 21:27
-
-
Save jmbarbone/b427440e2edc30c93386630660c4e2e0 to your computer and use it in GitHub Desktop.
base R windowing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window_apply <- function(x, n = 1, fun = mean) { | |
fun <- match.fun(fun) | |
if (n == 0) { | |
return(x) | |
} | |
s <- seq_along(x) | |
lower <- s - n | |
upper <- s + n | |
bad <- lower < 1 | |
upper[bad] <- upper[bad] + abs(lower[bad]) + 1L | |
lower[bad] <- which(bad) | |
bad <- upper > length(x) | |
lower[bad] <- lower[bad] - (upper[bad] - length(x)) | |
upper[bad] <- which(bad) | |
vapply( | |
seq_along(x), | |
function(i) { | |
fun(x[lower[i]:upper[i]]) | |
}, | |
NA_real_ | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment