R - Find "n" closest points to each point in SpatialPointsDataFrame
The geos
functions provided in sf
, combined with some matrix operations, will do the trick. First, convert and transform your points.
library(sf)
spbb # define your points here
spbb <- st_as_sf(spbb) # convert to simple features
spbb <- st_transform(spbb, 5880) # transform to your desired proj (unit = m)
Then, use st_distance
to create a matrix of distances between each point in the data frame. Replace the diagonal with NAs (because distance of a point to itself is 0).
dist_matrix <- st_distance(spbb, spbb) # creates a matrix of distances
diag(dist_matrix) <- NA # replaces 0s with NA
Lastly, use some matrix operations to get the smallest value of each row.
spbb$distance <- rowMins(dist_matrix) # get the dist of nearest element
spbb$nearest <- rowMins(dist_matrix, value = T) # get the index of the nearest element