开发者

Applying function to consecutive subvectors of equal size

开发者 https://www.devze.com 2023-04-04 17:21 出处:网络
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.

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 illustr开发者_开发技巧ate 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.


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号