Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying function to consecutive subvectors of equal size

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.

like image 240
eold Avatar asked Jan 18 '23 17:01

eold


1 Answers

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))
like image 71
G. Grothendieck Avatar answered Feb 02 '23 08:02

G. Grothendieck