I am working with a dataset that is similar to this one:
library(raster)
library(sf)
# Define CRSs
crs.latlon <- "+init=epsg:4326"
crs.sirgas <- "+init=epsg:5880"
# define edges in somewhere within brazil
(spbb <- matrix(c(-53,-44,-25,-20), nrow=2, byrow=F))
# create spatial points in lat/lon
spbb <- SpatialPoints(spbb, CRS(crs.latlon))
# convert to sirgas 2000
(spbb <- spTransform(spbb, CRS(crs.sirgas)))
# make a raster extent object rounded to km:
ext <- extent(5200000, 6046000, 7234000, 7756000)
# create raster
r <- raster(ext, ncol=252, nrow=156, crs=crs.sirgas) # ~3 km resolution
r[] <- runif(ncell(r)) * 10
# create station points
pts <- sampleRandom(r, 500, na.rm=TRUE, sp=TRUE, cells=T) #%>%
#plot(st_geometry(sf::st_as_sfc(pts)), col=sf.colors(4), axes = TRUE, cex=2, pch=19)
#check it
plot(r)
plot(pts, add=T, col="red", pch=19)
For each point in pts
, I would like to find the n (i.e. 5) closest surrounding ones. The resulting data frame would be something roughly similar to:
id nearest distance
pt1 pt3 14607
pt1 pt204 8540
pt1 pt301 6306
pt1 pt455 4956
pt1 pt337 2145
And so on for each point in the dataset.
What is the fastest way to achieve that?
knn
function in the spatialEco package will do exactly this, with the added ability to expand the problem into multivariate space (ie., add covariates in addition to distance).