Lachlan.00 Lachlan.00 - 1 year ago 58
R Question

R: Find closest value in large array and return dimensions

I'd like to find the nearest value to

in a large two dimensional array (
) and return the the i and j indexes where i is
and j is

x <- 1.863
my.array <- array(rnorm(21000), dim=c(175,120))

On searching on stack overflow and other sites I've found I can find the nearest value like so:

nearest <- which.min(abs(my.array - x))

However this returns a single locater value whereas I would like to return the i and j index values.

> nearest
[1] 13229

Thanks in advance.

Answer Source


... Use arrayInd(), if you need array/matrix indices instead of 1D vector ones.

# make the example reproducible
x <- 1.863
my.array <- array(rnorm(21000), dim=c(175,120))
nearest <- which.min(abs(my.array - x)) 
idx <- arrayInd(nearest, .dim=dim(my.array))
     [,1] [,2]
[1,]   46   62
# drop unused dimensions:
idx <- drop(idx)

[1] 46 62

# check:
my.array[idx[1], idx[2]]

[1] 1.863453

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download