zugabe - 8 months ago 61

R Question

Is there a simple and nice answer to this question?

I have a given list "l" of matrices (with same ncol & nrow).

`l<-lapply(1:10,function(x){`

matrix(runif(100),ncol=10)

})

I want the mean of every cell.

I could do that with a for loop, but there should be a better solution!

With two matrices I could do it with (m1+m2)/2.

But

`+`

`do.call(.Primitive("+"),l) / length(l)`

I'm looking forward for some nice answers :)

thanks in advance

Answer

Here are some alternatives:

**1) Reduce**

```
Reduce("+", l) / length(l)
```

**2) simlify2array/apply** A bit longer than (1); however, it does have the advadntage of readily extending to functions other than `mean`

:

```
apply(simplify2array(l), 1:2, mean)
```

**3) tapply** Not as simple but like (2) it extends to functions other than `mean`

:

```
array(tapply(unlist(l), sequence(sapply(l, length)), mean), dim(l[[1]]))
```

**4) rowMeans**

```
array(rowMeans(matrix(unlist(l), length(l[[1]]))), dim(l[[1]]))
```

Source (Stackoverflow)