CRAN_Status_Badge CRAN_Downloads_Badge

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

nngeo

The goal of nngeo is to provide k-nearest neighbor join capabilities for spatial analysis in R.

Installation

CRAN version:

install.packages("nngeo")

GitHub version:

install.packages("remotes")
remotes::install_github("michaeldorman/nngeo")

Documentation

The complete documentation can be found at https://michaeldorman.github.io/nngeo/.

Usage

Once installed, the library can be loaded as follows.

library(nngeo)

Example

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)


michaeldorman/nngeo documentation built on April 19, 2024, 12:04 a.m.