我想在矢量中找到最接近的值。我在这里使用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
但是我没有得到W矩阵的索引形式,它返回1,这是x中的位置。我做错了什么?