[R] Summing over an index of an array

Gavin Simpson gavin.simpson at ucl.ac.uk
Wed Feb 20 23:40:21 CET 2008


On Wed, 2008-02-20 at 13:39 -0800, Moshe Olshansky wrote:
> Try
> 
> apply(A,2:3,sum)

If speed is an issue, then colSums is a faster version of the above:

> A <- array(c(1:27), dim = c(3,3,3))
> (res1 <- apply(A, 2:3, sum))
     [,1] [,2] [,3]
[1,]    6   33   60
[2,]   15   42   69
[3,]   24   51   78

> (res2 <- colSums(A, dims = 1))
     [,1] [,2] [,3]
[1,]    6   33   60
[2,]   15   42   69
[3,]   24   51   78

> all.equal(res1, res2)
[1] TRUE

This is only really an issue with large arrays or for use in repeated
calculations.

> system.time(replicate(10000, apply(A, 2:3, sum)))
   user  system elapsed 
  2.766   0.018   2.928 
> system.time(replicate(10000, colSums(A, dims = 1)))
   user  system elapsed 
  0.563   0.006   0.596

HTH

G

> 
> --- Saurav Pathak <saurav at sas.upenn.edu> wrote:
> 
> > Hi,
> > 
> > I cannot seem to figure out how to sum over an index
> > of a array.
> > For example, let A be a 3 dimensional array.  I want
> > to, say, find
> > the sum over the first dimension.  That is
> > 
> >         S_jk = Sum_i A_ijk
> > 
> > where now S is a 2-dim matrix.  I dont want to use a
> > loop.
> > 
> > Thanks,
> > -- 
> > saurav
> > 
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained,
> > reproducible code.
> >
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list