# [R] maximum over one dimension of a 3-dimensional array

David Winsemius dwinsemius at comcast.net
Thu May 28 17:47:30 CEST 2009

```On May 28, 2009, at 11:25 AM, eric lee wrote:

> Hi,
>
> I'm running R 2.7.2 on windows XP.  I'd like to find the maximum of a
> 3-d array over it's third index to create a 2-d array.  For example:
>
>> x <- array(c(1,2,3,10,11,12,3:8),c(2,3,2))
>> x
> , , 1
>
>     [,1] [,2] [,3]
> [1,]    1    3   11
> [2,]    2   10   12
>
> , , 2
>
>     [,1] [,2] [,3]
> [1,]    3    5    7
> [2,]    4    6    8
>
>> x1 <- x[,,1]
>> x2 <- x[,,2]
>> pmax(x1,x2)
>     [,1] [,2] [,3]
> [1,]    3    5   11
> [2,]    4   10   12

Consider:

> apply(x, 1:2, max)
[,1] [,2] [,3]
[1,]    3    5   11
[2,]    4   10   12

or

> apply(x, c(1,2), max)  # not necessarily adjacent dimensions
[,1] [,2] [,3]
[1,]    3    5   11
[2,]    4   10   12

>

>
> Is there a pre-defined function that I can use to do this without
> using a for-loop?  Also, the third index can be long and of variable
> length, so I don't want to explicitly write out x1, x2,...  Thanks in