st_nb_apply: Apply a function to neighbors

View source: R/apply.R

st_nb_applyR Documentation

Apply a function to neighbors

Description

Sometimes one may want to create custom lag variables or create some other neighborhood level metric that may not be defined yet. This st_nb_apply() enables you to apply a function to each observation's (xi) neighbors (xij).

Usage

st_nb_apply(x, nb, wt, .f, suffix = "dbl", ...)

Arguments

x

A vector that will be used for neighbor xij values.

nb

A neighbor list object as created by st_neighbors().

wt

A weights list as created by st_weights().

.f

A function definition. There are three default objects that can be used inside of the function definition:

  • .xij: neighbor values of x for the ith observation. This is simply the subset of x based on the corresponding nb list values for each element.

  • .nb: neighbor positions.

  • .wt: neighbor weights value.

If any of these three function arguments are omitted from .f, dots (...) must be supplied.

suffix

The map variant to use. Options are "dbl", "int", "lgl", "chr", "list".

...

arguments to pass to .f

Details

The below example calculates the spatial lag using st_nb_apply() and st_lag() to illustrate how we can apply functions to neighbors.

Currently questioning the use case. find_xj() is now exported and may negate the need for this function.

Value

a vector or list of with same length as x.

Examples

if (requireNamespace("dplyr", quietly = TRUE)) {
library(magrittr)
guerry %>%
  dplyr::transmute(
    nb = st_contiguity(geometry),
    wt = st_weights(nb),
    lag_apply = st_nb_apply(
      crime_pers, nb, wt,
      .f = function(.xij, .wt, ...) sum(.xij *.wt)
    ),
    lag = st_lag(crime_pers, nb, wt)
  )
}

JosiahParry/sfdep documentation built on Sept. 7, 2024, 6:15 a.m.