Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to identify positions of max value in an array?

Tags:

arrays

r

max

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?

like image 391
Dan Avatar asked Oct 03 '22 10:10

Dan


1 Answers

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.

like image 183
Simon O'Hanlon Avatar answered Oct 12 '22 11:10

Simon O'Hanlon