Reputation: 1
I have a several problem in the following task:
I have vector w=c(1,4,8,8,6,3,11,24,16)
and k=9
The next task is to print the index of strings (from the w) where the nearest numbers to the k are.
The next code prints the only one index (5th or 6th string of vector w) and does not consider that the vector has the two same numbers - 8 which are more nearest to the k=9. But it's needed to print all relevant indexes (in this case 5 and 6 - numbers of corresponding strings). How to print all relevant indexes?
dt = data.table(w, val = w)
setkey(dt,w)
dt[J(k), roll = "nearest"]
d1=dt[J(k), .I, roll = "nearest", by = .EACHI]
d1[,2]
Upvotes: 0
Views: 58
Reputation: 791
I would do something like below:
w <- c(1,4,8,8,6,3,11,24,16)
k <- 9
distances <- abs(k-w)
which(distances == min(distances))
Upvotes: 1