Applying function to consecutive subvectors of equal size

前端 未结 3 2037
花落未央
花落未央 2021-01-13 20:08

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

3条回答
  •  有刺的猬
    2021-01-13 20:37

    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.

提交回复
热议问题