Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Last active October 2, 2023 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbarbone/b427440e2edc30c93386630660c4e2e0 to your computer and use it in GitHub Desktop.
Save jmbarbone/b427440e2edc30c93386630660c4e2e0 to your computer and use it in GitHub Desktop.
base R windowing
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