2

I am trying to find the nearest value in vector. I found the solution in here using data.table

Find closest value in a vector with binary search

x=4.5
w=c(1,2,4,6,7)
dt = data.table(w, val = w) # you'll see why val is needed in a sec
setattr(dt, "sorted", "w")  # let data.table know that w is sorted
dt[J(x), .I, roll = "nearest"]
#     w .I
#1: 4.5  3

However I do not get the index form W matrix, it returns 1 which is the location in x. What am I doing wrong?

Community
  • 1
  • 1
newbie
  • 757
  • 1
  • 9
  • 19
  • It doesn't work for me neither. I'm not sure how it did in previous versions. Though `dt[J(x), val, roll = "nearest"]` will give you the value while `dt[J(x), which = TRUE, roll = "nearest"]` will give you the locaiton – David Arenburg Dec 07 '15 at 17:08
  • Perfect. It is exactly what I was looking for. Thanks – newbie Dec 07 '15 at 17:10
  • @DavidArenburg make it an answer :) – jangorecki Dec 07 '15 at 22:07
  • 2
    @jangorecki it seems actually that adding `by = .EACHI` is the answer but I can't explain why. So probably this is a task for @Arun or @eddi. – David Arenburg Dec 07 '15 at 22:32
  • yes, that's it - the answer was written in the olden days when by-without-by was a hidden default; closing as duplicate – eddi Dec 09 '15 at 16:33

0 Answers0