Navin Manaswi
Navin Manaswi

Reputation: 992

Searching the closest value in other column

Suppose we have a data frame of two columns

 X    Y 
 10  14 
 12  16   
 14  17  
 15  19   
 21  19

The first element of Y that is 14, the nearest value (or same) to it is 14 (which is 3rd element of X). Similarly, next element of Y is closest to 15 that is 4th element of X

So, the output I would like should be

3
4
4
5
5

As my data is large, Can you give me some advice on the systemic/proper code for doing it?

Upvotes: 0

Views: 42

Answers (1)

Marat Talipov
Marat Talipov

Reputation: 13304

You can try this piece of code:

apply(abs(outer(d$X,d$Y,FUN = '-')),2,which.min)
# [1] 3 4 4 5 5

Here, abs(outer(d$X,d$Y,FUN = '-')) returns a matrix of unsigned differences between d$X and d$Y, and apply(...,2,which.min) will return position of the minimum by row.

Upvotes: 1

Related Questions