I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as sum
, consecutively to a subvector of consecutive K e
As @Chase said in a comment, you can create your own grouping variable and then use that. Wrapping that process into a function would look like
myapply <- function(v, fun, group_size=1) {
unname(tapply(v, (seq_along(v)-1) %/% group_size, fun))
}
which gives your results
> myapply(v, sum, group_size=3)
[1] 6 15 15
Note this does not require the length of v
to be a multiple of the group_size
.