[R] blockwise sums
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Aug 31 15:03:14 CEST 2004
Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:
> 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
Slight variant
pd.blockwisesum <-
function(v,n){N <- length(v); tapply(x,gl(ceiling(N/n), n, N), sum)}
> pd.blockwisesum(1:10,3)
1 2 3 4
6 15 24 10
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list