# [R] blockwise sums

Wolski wolski at molgen.mpg.de
Tue Aug 31 14:40:06 CEST 2004

```Hi!

ind<-c(sort(rep(1:floor(length(x)/ 3 ) ,  3 )) , floor(length(x)/ 3 )+1)

by(x,ind,sum)

my.blockwisesum<-function(x,n,...)
{
ind<-c(sort(rep(1:floor(length(x)/ n ) ,  n )) , floor(length(x)/ n )+1)
return(tapply(x,ind,sum))
}

/Eryk

*********** REPLY SEPARATOR  ***********

On 8/31/2004 at 2:19 PM Lutz Prechelt wrote:

>>>I am looking for a function like
>>>  my.blockwisesum(vector, n)
>>>that computes sums of disjoint subsequences of length n from vector
>>>and can work with vector lengths that are not a multiple of n.
>>>
>>>It should give me for instance
>>>  my.blockwisesum(1:10, 3) == c(6, 15, 24, 10)
>>>
>>>Is there a builtin function that can do this?
>>>One could do it by coercing the vector into a matrix of width n,
>>>and then use apply,
>>>but that is cumbersome if the length is not divisible by n,
>>>is it not?
>>>Any other ideas?
>>>
>>>  Lutz
>>>
>>>Prof. Dr. Lutz Prechelt;  prechelt at inf.fu-berlin.de
>>>Institut fuer Informatik; Freie Universitaet Berlin
>>>Takustr. 9; 14195 Berlin; Germany
>>>+49 30 838 75115; http://www.inf.fu-berlin.de/inst/ag-se/
>>>
>>>______________________________________________
>>>R-help at stat.math.ethz.ch mailing list
>>>https://stat.ethz.ch/mailman/listinfo/r-help
>>>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Dipl. bio-chem. Witold Eryk Wolski             @         MPI-Moleculare Genetic
Ihnestrasse 63-73 14195 Berlin                'v'
tel: 0049-30-83875219                        /   \
mail: witek96 at users.sourceforge.net        ---W-W----    http://www.molgen.mpg.de/~wolski
wolski at molgen.mpg.de

```