cs0815
cs0815

Reputation: 17388

finding closest value in vector produces unexpected result

I am using this code (taken from here):

values <- seq(0, 100, 5)
value <- 91

which(abs(values - value) == min(abs(values - value)))

It should produce 90 but returns 19?! Any idea why? Thanks!

Upvotes: 1

Views: 38

Answers (2)

GKi
GKi

Reputation: 39657

which will give the TRUE indices of a logical object, and those can then be used to subset the vector to get the value. So either you use:

values[which(abs(values - value) == min(abs(values - value)))]
#[1] 90

where which could also be removed

values[abs(values - value) == min(abs(values - value))]
#[1] 90

In case you want only the first hit which.min could be used.

values[which.min(abs(values - value))]
#[1] 90

Also findInterval could be an option in case values is sorted and one result per value is wanted. This uses binary search and could be faster in case many nearest values are searched. In case values in not sorted it needs to be sorted for this method.

values[findInterval(value, values[-1] - diff(values)/2) + 1]
#[1] 90

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

The code returns the position, you need to use it to get the actual value from values.

values[which(abs(values - value) == min(abs(values - value)))]
#[1] 90

Or with a temporary variable.

tmp <- abs(values - value) 
values[which(tmp == min(tmp))]

Upvotes: 2

Related Questions