R – How to Select Multiple Points Closest to a Set of Coordinates

knnlidrr

Given a LAS object with x,y,z coordinates, i.e

LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las = readLAS(LASfile, select = "xyz")

and a set of x,y,z coordinates (GCPs),

I seek a function that should return, for each point in the GCPs matrix, the x,y,z coordinates of the point in the LAS object that is the closest (Euclidean distance) using the x,y coordinates only.

I want to compare the z coordinates of the selected points in the cloud to the z coordinates of the set of GCPs

Best Answer

There are tools like that in lidR but they are internal tools not exposed to users yet. But R has plenty of nearest neighbour search packages such as nabor. Below a reproducible exemple

LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las <- readLAS(LASfile, select = "xyz")
x <- runif(10, min(las$X), max(las$X))
y <- runif(10, min(las$Y), max(las$Y))
M <- cbind(x,y)

NN <- nabor::knn(las@data[,c("X", "Y")], M, k = 1)

sub <- las[as.numeric(NN$nn.idx)]
sub
plot(sub)
Related Question