0

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?

J Richard Snape
  • 20,116
  • 5
  • 51
  • 79
Navin Manaswi
  • 964
  • 7
  • 19
  • Welcome to Stack overflow! This is not a code-swapping site, so in general questions like "can you give me the code to do...." are likely to irritate a lot of users. Instead - post what you've tried, or which dataframe R documentation you've looked at and why it didn't work for you / what you can't understand. If you hit error messages, post them too. If you haven't already - read [how to ask a good question](http://stackoverflow.com/help/how-to-ask), that's a good starting point to get the best help from the site. – J Richard Snape Feb 10 '15 at 16:52

1 Answers1

1

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.

Marat Talipov
  • 13,064
  • 5
  • 34
  • 53