# Re: [R] apply mean to a three-dimension data

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Thu, 24 Mar 2011 16:26:14 -0400

Are you taking the same online course as Barth Riley, who posed a very similar question only this morning?

On Mar 24, 2011, at 11:07 AM, Hui Du wrote:

> Hi All,
>
> Suppose I have data like
>
> b[] = matrix(1:4, 2, 2)
> b[] = matrix(10:13, 2, 2)
> b[] = matrix(20:23, 2, 2)
>
> []
> [,1] [,2]
> [1,] 1 3
> [2,] 2 4
>
> []
> [,1] [,2]
> [1,] 10 12
> [2,] 11 13
>
> []
> [,1] [,2]
> [1,] 20 22
> [2,] 21 23
>
> Now I want to calculate the mean of each cell across
> the list. For example mean of (b[][1,1], b[][1,1], b[]
> [1,1]), mean of (b[][1,2], b[][1,2], b[][1,2]) etc. e.g.
> mean of (1, 10, 20), mean of(3, 12, 22). Could somebody tell me how
> to do it? Thank you in advance.

> vec <- do.call("c", b) # turns values into a long vector  > dim(vec) <- c(length(b[], length(b)) # "folds" it, so it is three columns "wide"
> rowMeans(vec)
 10.33333 11.33333 12.33333 13.33333

This is done in row-major order as are all of R's matrix operations, so it's not exactly what you asked for, but you will need to get used to row-first order if you're going to use R.

```--

David Winsemius, MD
West Hartford, CT

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help