knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" )
The goal of nngeo
is to provide k-nearest neighbor join capabilities for spatial analysis in R.
CRAN version:
install.packages("nngeo")
GitHub version:
install.packages("remotes") remotes::install_github("michaeldorman/nngeo")
The complete documentation can be found at https://michaeldorman.github.io/nngeo/.
Once installed, the library can be loaded as follows.
library(nngeo)
The following code section finds the 20-nearest towns for each city using function st_nn
.
data(towns) data(cities) nn = st_nn(cities, towns, k = 20, progress = FALSE) nn
By default, the result is a sparse list with the neighbor IDs.
The st_nn
function can also be used as a geometry predicate function when performing spatial join with sf::st_join
.
st_join(cities, towns, join = st_nn, k = 3, progress = FALSE)
A helper function st_connect
can be used to draw lines according to joined feature IDs. This may be useful for visualization or for network analysis.
l = st_connect(cities, towns, ids = nn, progress = FALSE) plot(l, col = NA) # For setting the extent plot(st_geometry(towns), col = "darkgrey", add = TRUE) plot(st_geometry(cities), col = "red", add = TRUE) plot(l, add = TRUE)
opar = par(mar = rep(0.5, 4)) l = st_connect(cities, towns, ids = nn, progress = FALSE) plot(l, col = NA) # For setting the extent plot(st_geometry(towns), col = "darkgrey", add = TRUE) plot(st_geometry(cities), col = "red", add = TRUE) plot(l, add = TRUE) par(opar)
x = list.files(pattern = "^README-.*\\.png$") file.copy(x, "docs/", overwrite = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.