I have two data tables with x,y coordinates and some other info which I would like to merge based on nearest neighbour distance, i.e. on the minimum in squared difference of
One possible solution:
func = function(u,v) { vec = with(DT2, (u-x)^2 + (v-y)^2) DT2[which.min(vec),]$Q } transform(DT1, Q=apply(DT1, 1, function(u) func(u[1], u[2]))) # x y Q #1: 1 3 a #2: 2 4 d #3: 3 5 d #4: 4 6 e #5: 5 7 e