Eduardo de Oliveira Horta
2010-Dec-27 22:26 UTC
[R] Finding indexes of minum and maximum elements of an array
Hello there I wish to get the "coordinates" of the minimum element of an array. For example, if the array were> H = array(c(8:5,1:4),dim=c(2,2,2)) > H, , 1 [,1] [,2] [1,] 8 6 [2,] 7 5 , , 2 [,1] [,2] [1,] 1 3 [2,] 2 4 then> min(H)[1] 1 and> max(H)[1] 8 Say "idx" were the function I'm looking for. Then, what I'm expecting is> idx(min(H))[1] 1 1 2> idx(max(H))[1] 1 1 1 Thanks in advance, Eduardo de Oliveira Horta [[alternative HTML version deleted]]
Duncan Murdoch
2010-Dec-27 22:44 UTC
[R] Finding indexes of minum and maximum elements of an array
On 10-12-27 5:26 PM, Eduardo de Oliveira Horta wrote:> Hello there > > I wish to get the "coordinates" of the minimum element of an array. > > For example, if the array were > >> H = array(c(8:5,1:4),dim=c(2,2,2)) >> H > , , 1 > > [,1] [,2] > [1,] 8 6 > [2,] 7 5 > > , , 2 > > [,1] [,2] > [1,] 1 3 > [2,] 2 4 > > then >> min(H) > [1] 1 > > and >> max(H) > [1] 8 > > Say "idx" were the function I'm looking for. Then, what I'm expecting is > >> idx(min(H)) > [1] 1 1 2 >> idx(max(H)) > [1] 1 1 1I don't know if anyone has written a function with the exact output you want, but you can get the vector index using which.min() and which.max(). Converting that to a vector index is simply a matter of some modular arithmetic. Here's a quick ugly version: vector.which.min <- function(H) { d <- dim(H) i <- which.min(H) - 1 result <- c() for (j in seq_along(d)) { result <- c(result, i %% d[j]) i <- i %/% d[j] } result + 1 } Duncan Murdoch
Phil Spector
2010-Dec-28 00:17 UTC
[R] Finding indexes of minum and maximum elements of an array
Here's one way:> H = array(c(8:5,1:4),dim=c(2,2,2)) > which(H==min(H),arr.ind=TRUE)dim1 dim2 dim3 [1,] 1 1 2> which(H==max(H),arr.ind=TRUE)dim1 dim2 dim3 [1,] 1 1 1 - Phil Spector Statistical Computing Facility Department of Statistics UC Berkeley spector at stat.berkeley.edu On Mon, 27 Dec 2010, Eduardo de Oliveira Horta wrote:> Hello there > > I wish to get the "coordinates" of the minimum element of an array. > > For example, if the array were > >> H = array(c(8:5,1:4),dim=c(2,2,2)) >> H > , , 1 > > [,1] [,2] > [1,] 8 6 > [2,] 7 5 > > , , 2 > > [,1] [,2] > [1,] 1 3 > [2,] 2 4 > > then >> min(H) > [1] 1 > > and >> max(H) > [1] 8 > > Say "idx" were the function I'm looking for. Then, what I'm expecting is > >> idx(min(H)) > [1] 1 1 2 >> idx(max(H)) > [1] 1 1 1 > > Thanks in advance, > > Eduardo de Oliveira Horta > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >