Given:
x <- c(1, 2, 3, 4, 7, 9, 2, 4)
You can see the function embed:
embed(x, 3)
# [,1] [,2] [,3]
# [1,] 3 2 1
# [2,] 4 3 2
# [3,] 7 4 3
# [4,] 9 7 4
# [5,] 2 9 7
# [6,] 4 2 9
Please note that this is not the correct length, and that we are not interested in the first line, so let's make a modification:
embed(c(x[-1], 0, 0, 0), 3)
# [,1] [,2] [,3]
# [1,] 4 3 2
# [2,] 7 4 3
# [3,] 9 7 4
# [4,] 2 9 7
# [5,] 4 2 9
# [6,] 0 4 2
# [7,] 0 0 4
# [8,] 0 0 0
From there it should be simple:
apply(embed(c(x[-1], 0, 0, 0), 3), 1, max)
# [1] 4 7 9 9 9 4 4 0
For convenience, as a function:
this_by_n <- function(invec, n = 3, pad_val = NA, FUN = sum) {
FUN <- match.fun(FUN)
apply(embed(c(invec[-1], rep(pad_val, n)), n), 1, {
function(x) if (all(is.na(x))) NA else FUN(x[!is.na(x)])
})
}
Try:
this_by_n(x, 3, NA, mean)
this_by_n(x, 2, NA, max)
this_by_n(x, 4, NA, min)