bquast - 11 months ago 63

R Question

I would like to know how to turn a 3d array into a matrix, by e.g. summing, averaging, or taking the maximum or minimum over the 3rd dimension.

This sounds like something that would have already been asked, I did look around quite a bit but couldn't find exactly this.

A MWE would be:

`> a3 <- array(c(1:9, 1:9), c(3,3,2))`

> a3

, , 1

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

, , 2

[,1] [,2] [,3]

[1,] 1 4 7

[2,] 2 5 8

[3,] 3 6 9

Answer Source

The simplest way appears to be using `apply()`

.

```
> apply(a3, 1:2, sum)
[,1] [,2] [,3]
[1,] 2 8 14
[2,] 4 10 16
[3,] 6 12 18
```

Where `1:2`

are passed to the `MARGIN`

argument and represent the dimensions of the input object (`X`

) to be preserved.

**Note that this also applies to higher dimensional arrays.**

For `mean()`

this would of course be:

```
> apply(a3, 1:2, mean)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
```

and similarly you can use `min()`

, `max()`

, etc.