[R] blockwise sums

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Aug 31 14:36:25 CEST 2004


Liaw, Andy wrote:
> If you insist, here's one way:
> 
> my.blockwisesum <- function(x, n, ...) {
>     tapply(x, seq(1, length(x), by=n), sum, ...)
> }
> 

  Did you test that? I get:

 > my.blockwisesum(1:10, 3)
Error in tapply(x, seq(1, length(x), by = n), sum, ...) :
         arguments must have same length


  Here's my solution with tapply and rep() to generate a vector like 
c(1,1,1,2,2,2,3,3,3,4):

baz.blockwisesum=
  function(v,n){tapply(v,rep(1:(1+length(v)/n),each=n)[1:length(v)],sum)}

 > baz.blockwisesum(1:10,3)
  1  2  3  4
  6 15 24 10

  - just ignore the 1 to 4 names, they cant hurt you.

Baz




More information about the R-help mailing list