[R] function sum for array
R. Michael Weylandt
michael.weylandt at gmail.com
Thu Nov 17 21:39:12 CET 2011
It might not be as general as you have in mind, but this works:
X = array(1:24, c(2,3,4))
rowSums(X, dims = 2)
Combined with aperm() it's pretty powerful.
Michael
On Thu, Nov 17, 2011 at 11:24 AM, Simone Salvadei
<simone.salvadei at gmail.com> wrote:
> I'm looking for a function that allows to sum the elements of an array
> along a dimension that can be different from the classical ones (rows or
> columns).
>
> Let's suppose for example that:
>
> - A is an array with dimensions 2 x 3 x 4
> - I want to compute B, a 2 x 3 matrix with elements equal to the sum of the
> corrensponding elements on each of the 3 strata.
>
> I've tried to use apply(A,3,sum) but the result is a vector, not a matrix.
> Another solution is a less elegant
>
> B=matrix(rep(0,6),ncol=3)
> for(t in 1:4) B = B + A[ , , t]
>
> May anybody help?
> S
>
> --
> -------------------------------------------------------------------
>
> Simone Salvadei
>
> Faculty of Economics
> Department of Financial and Economic Studies and Quantitative Methods
> University of Rome Tor Vergata
> e-mail: simone.salvadei at uniroma2.it <federico.belotti at uniroma2.it>
> url: http://www.economia.uniroma2.it/phd/econometricsempiricaleconomics/
> <http://www.econometrics.it/>
> -------------------------------------------------------------------
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list