Applying function to consecutive subvectors of equal size

两盒软妹~` 提交于 2019-12-01 06:33:22
G. Grothendieck

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))

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.

You could try this as well. This works nicely even if you want to include overlapping intervals, as controlled by by, and as a bonus, returns the intervals over which each value is derived:

library (gtools)
v2 <- running(v, fun=sum, width=3, align="left", allow.fewer=TRUE, by=3)

v2
1:3 4:6 7:8 
  6  15  15 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!