[R] Average of Two Matrices

Joshua Wiley jwiley.psych at gmail.com
Thu Dec 1 08:25:32 CET 2011


Well, you're rather stuck writing them all out unless you have them in
some other data structure.

## three dimensional array (50 4 x 4 matrices)
x <- array(rnorm(16 * 50), dim = c(4, 4, 50))
> apply(x, 1:2, mean)
            [,1]        [,2]         [,3]        [,4]
[1,] -0.09460574  0.01572077 -0.166194625 -0.28176540
[2,] -0.26649044 -0.23546332 -0.003559647 -0.09857819
[3,]  0.12657883  0.10979631  0.368414189 -0.13653997
[4,] -0.02827496  0.07634844 -0.088057890  0.06208034
## list of length 50 each element is 4 x 4 matrix
> y <- rep(list(matrix(rnorm(16), 4, 4)), 50)
> length(y)
[1] 50
> Reduce(`+`, y)/length(y)
           [,1]        [,2]        [,3]       [,4]
[1,] -1.8334660  0.67812999  0.20159314  1.6163501
[2,] -0.6716821 -0.23942474 -0.50482638 -0.5765309
[3,]  0.7991496  0.38674047 -0.02128386 -1.1868209
[4,] -1.1654429  0.06773386  0.13538268  0.3847375

See ?array ?apply ?Reduce for documentation

Hope this helps,

Josh

On Wed, Nov 30, 2011 at 7:22 PM, T.D. Rudolph <tylerdrudolph at gmail.com> wrote:
>
> What if you have over 50 matrices and you don't want to write them all out
> one-by-one?  I know there's something really quite simple, but I haven't
> found it yet!...
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Average-of-Two-Matrices-tp860672p4126615.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list