Re: [R] Summing over an index of an array

From: Gavin Simpson <gavin.simpson_at_ucl.ac.uk>
Date: Wed, 20 Feb 2008 22:40:21 +0000

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@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
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

______________________________________________
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.
Received on Wed 20 Feb 2008 - 22:48:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 20 Feb 2008 - 23:30:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive