In my dataset, I have points, whose location are given by X and Y, that are grouped by ID. I want to calculate the nearest neighbour (NN) distance of each point to the points in other groups. In other words, if the ID of a point is 1, the code should search for the NND from the points that satisfy ID != 1.
A pseudo-R-code could look like this:
DT[DT, c("nn_dist", "nn_X", "nn_Y") := find_NNN(data.table(i.X, i.Y), .SD[ID != i.ID]), by = .EACHI]
To achieve this, I tried writing an imperative code with loops and such, but it was too slow. I tried using get.knnx function from FNN library but then I couldn't figure out how to get both the NN distance and the position of the NN.
How can I do this calculation on a relatively large (~10,000 rows) dataset?
Here is a tiny portion of the dataset I'm using
structure(list(ID = c(1L, 1L, 2L, 2L), X = c(318L, 317L, 1273L,
1272L), Y = c(1L, 2L, 1L, 2L), t = c(1, 1, 1, 1), uid = c(1L,
2L, 1271L, 1272L)), row.names = c(NA, -4L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7f89b481f0e0>)
tcolumn is the same for all of the points in the datasetuidis a unique id given to every point, regardless of their position or group, somax(uid)equals to the #rows in the dataset