R: find the nearest index

I have two vectors with several thousand points, but they are generalized here:

A <- c(10, 20, 30, 40, 50) b <- c(13, 17, 20) 

How to get signs A that are closest to b ? The expected result will be c(1, 2, 2) .

I know that findInterval can only find the first occurrence, not the nearest one, and I know which.min(abs(b[2] - A)) getting warmer, but I cannot figure out how to vectorize it to work with long vectors of both A and b .

+6
source share
3 answers

You can just add your code to sapply. I think this has the same speed as the for loop, so it is not technically vectorized:

 sapply(b,function(x)which.min(abs(x - A))) 
+11
source

FindInterval takes you very close. You just need to choose between the offset it returns and the following:

 #returns the nearest occurence of x in vec nearest.vec <- function(x, vec) { smallCandidate <- findInterval(x, vec, all.inside=TRUE) largeCandidate <- smallCandidate + 1 #nudge is TRUE if large candidate is nearer, FALSE otherwise nudge <- 2 * x > vec[smallCandidate] + vec[largeCandidate] return(smallCandidate + nudge) } nearest.vec(b,A) 

returns (1,2,2) and is comparable to FindInterval in performance.

+11
source

Here, a solution that uses R often skips the outer function. Not sure if it will work better, but it avoids sapply .

 A <- c(10, 20, 30, 40, 50) b <- c(13, 17, 20) dist <- abs(outer(A, b, '-')) result <- apply(dist, 2, which.min) # [1] 1 2 2 
0
source

Source: https://habr.com/ru/post/913231/


All Articles