0

I have a frame

J = data.frame(Entry = c(100, 5, 10, 20, 35))

For each record I want to find the nearest value and end up with

Entry | nearest
 100  |  35
 5    |  10
 20   |  10
 35   |  20

I looked at the data table code Find closest value in a vector with binary search

but because for Entry I am trying to find the closest value it just returns the vector that I enter. How can I do this?

Community
  • 1
  • 1
KillerSnail
  • 3,321
  • 11
  • 46
  • 64
  • I think the answer you are looking for is in [here](https://stat.ethz.ch/pipermail/r-help/2013-September/359974.html) – Sotos Feb 24 '16 at 14:05

1 Answers1

2
J <- data.frame(Entry = c(100, 5, 10, 20, 35), 
               X = sapply(J$Entry, function(x){
  temp <- J$Entry[!J$Entry == x]
  temp[which.min(abs(temp - x))]
}))

> J
  Entry  X
1   100 35
2     5 10
3    10  5
4    20 10
5    35 20

Like this?

statespace
  • 1,644
  • 17
  • 25