coolhand
coolhand

Reputation: 2061

Return Indices Of Maximum Value in a Multidimensional Array in R

Does R have a way to return the indices for the largest value in a multidimensional array?

I'm aware of the which.max() function for a vector, but I'm not sure if there is a similar way to return a set of indices for a multi-dimensional array.

For example, if I have a set of random values stored in a 35x55x1000 3D array:

test <- array(rnorm(35*55*1000, mean=5, sd=1), dim=c(35,55,1000))

and I want to find the indices related to the maximum value in in the 2D slice test[,20,]

using which.max(test[,20,]) provides a single value, not a set of indices. Is there a way to do this without creating some sort of loop function (that might be slow)?

Upvotes: 1

Views: 1072

Answers (1)

coolhand
coolhand

Reputation: 2061

This provides the answer I was looking for in the format of [x1, x2, x3] where x2=20:

which( test==max(test[,20,],na.rm=T) , arr.ind = T )

If the indices in the matrix are wanted without constraining it to a 2D by setting x2=20, you can use the below line:

which( test==max(test,na.rm=T) , arr.ind = T )

If there are multiple indices sets that have the same maximum value, you can select the first set from the list with

which( test==max(test,na.rm=T) , arr.ind = T )[1,]

Upvotes: 1

Related Questions