[R] blockwise sums
Dimitris Rizopoulos
dimitris.rizopoulos at med.kuleuven.ac.be
Tue Aug 31 14:51:18 CEST 2004
Hi Lutz,
you could try the following:
blockwisesum <- function(x, n){
nx <- length(x)
if(nx%%n) x. <- c(x, rep(0., n*ceiling(nx/n)-nx)) else x. <- x
x. <- matrix(x., ncol=n, byrow=TRUE)
rowSums(x.)
}
blockwisesum(1:10, 3)
I hope this helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Doctoral Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/396887
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Lutz Prechelt" <prechelt at pcpool.mi.fu-berlin.de>
To: <r-help at stat.math.ethz.ch>
Sent: Tuesday, August 31, 2004 2:19 PM
Subject: [R] blockwise sums
> 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
More information about the R-help
mailing list