bic ton
bic ton

Reputation: 1408

How to compute max from array?

This an array:

 a <- array(1:16, c(2, 2, 2))

my desir output is this:

                [,1] [,2]
          [1,]    5    7
          [2,]    6    8

I tried these but not what I wanted:

      apply(a,2,max)
      max(a)

Upvotes: 0

Views: 29

Answers (1)

akrun
akrun

Reputation: 886948

We need to specify the MARGIN correctly to apply the max on the coresponding elements

apply(a, c(1, 2), max)
#.     [,1] [,2]
#[1,]    5    7
#[2,]    6    8

If we are using matrixStats, then with rowMaxs, the same MARGIN from OP's post should work

library(matrixStats)
apply(a, 2, rowMaxs)

Upvotes: 1

Related Questions