Lachlan.00 - 2 months ago 8

R Question

I'd like to find the nearest value to

`x`

`my.array`

`[1:175]`

`[1:120]`

`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

`help(which.min)`

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

```
# make the example reproducible
set.seed(123)
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))
idx
```

`[,1] [,2] [1,] 46 62`

```
# drop unused dimensions:
idx <- drop(idx)
idx
```

[1] 46 62

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

[1] 1.863453

Source (Stackoverflow)

Comments