Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find nearest value in vector

Tags:

r

I have two integer/posixct vectors:

a <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) #has > 2 mil elements
b <- c(4,6,10,16) # 200000 elements

Now my resulting vector c should contain for each element of vector a the nearest element of b:

c <- c(4,4,4,4,4,6,6,...)

I tried it with apply and which.min(abs(a - b)) but it's very very slow.

Is there any more clever way to solve this? Is there a data.table solution?

like image 876
MikeHuber Avatar asked Apr 18 '17 06:04

MikeHuber


People also ask

How do I find the closest value to a number in R?

To find the row corresponding to a nearest value in an R data frame, we can use which. min function after getting the absolute difference between the value and the column along with single square brackets for subsetting the row.

How do you find the closest value in an array?

Find the closest value in array using reduce() The easiest way to do this is to use Math. abs(), so lets use that. With this function we check whether the absolute value of (b – 8) is less than the absolute value of (a – 8) and then return the winner.

How do you find the nearest number in a set?

If set is not ordered, just iterate through the set, (Sorting it would itself take more than one pass), and for each member, check to see if the difference is smaller than the smallest difference you have seen so far, and if it is, record it as the new smallest difference, and that number as the new candidate answer. .


1 Answers

As it is presented in this link you can do either:

which(abs(x - your.number) == min(abs(x - your.number)))

or

which.min(abs(x - your.number))

where x is your vector and your.number is the value. If you have a matrix of dataframe, simply convert them to numeric vector with appropriate ways and then try this on the resulting numeric vector.

like image 118
Mehrad Mahmoudian Avatar answered Sep 27 '22 22:09

Mehrad Mahmoudian