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?