Applying function to consecutive subvectors of equal size

不问归期 提交于 2019-12-01 05:18:36

问题


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 elements. Here is one simple example, which should illustrate very clearly what I want:

v <- c(1, 2, 3, 4, 5, 6, 7, 8)
v2 <- myapply(v, sum, group_size=3) # v2 should be equal to c(6, 15, 15)

The function should try to process groups of group_size elements of a given vector and apply a function to each group (treating it as another vector). In this example, the vector v2 is obtained as follows: (1 + 2 + 3) = 6, (4 + 5 + 6) = 15, (7 + 8) = 15. In this case, the K did not divide N exactly, so the last group was of size less then K.

If there is a nicer/faster solution which only works if N is a multiple of K, I would also appreciate it.


回答1:


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



回答2:


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.




回答3:


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 


来源:https://stackoverflow.com/questions/7420815/applying-function-to-consecutive-subvectors-of-equal-size

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