Applying function to consecutive subvectors of equal size

前端 未结 3 2072
花落未央
花落未央 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:29

    Try this:

    library(zoo)
    rollapply(v, 3, by = 3, sum, partial = TRUE, align = "left")
    ## [1]  6 15 15
    

    or

    apply(matrix(c(v, rep(NA, 3 - length(v) %% 3)), 3), 2, sum, na.rm = TRUE)
    ## [1]  6 15 15
    

    Also, in the case of sum the last one could be shortened to

    colSums(matrix(c(v, rep(0, 3 - length(v) %% 3)), 3))
    

提交回复
热议问题