how to identify positions of max value in an array

2019-06-23 17:15发布

问题:

My array is

x <- array(1:24, dim=c(3,4,3))

My task 1 is to find the max value according to the first two dimensions

x.max <- apply(x,c(1,2), function(x) ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE)))    

in case there is NA data my task 2 is to find the max value position on the third dimension. I tried

x.max.position = apply(x, c(1,2),which.max(x))

But this only give me the position on the fist two dimensions.

Can anyone help me?

回答1:

It's not totally clear, but if you want to find the max for each matrix of the third dimension (is that even a technically right thing to say?), then you need to use apply across the third dimension. The argument margin under ?apply states that:

a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.

So for this example where you have a 3D array, 3 is the third dimension. So...

t( apply( x , 3 , function(x) which( x == max(x) , arr.ind = TRUE ) ) ) 
     [,1] [,2]
[1,]    3    4
[2,]    3    4
[3,]    3    4

Which returns a matrix where each row contains the row and then column index of the max value of each 2D array/matrix of the third dimension.

If you want the max across all dimensions you can use which and the arr.ind argument like this:

which( x==max(x,na.rm=T) , arr.ind = T )
     dim1 dim2 dim3
[1,]    3    4    2

Which tells us the max value is the third row, fourth column, second matrix.

EDIT

To find the position at dim 3 where where values on dim 1 and 2 are max try:

which.max( apply( x , 3 , max ) )
# [1] 2

Which tells us that at position 2 of the third dimension contains the maximal value.



标签: arrays r max