st_extract_within: Extract information from geometry that a point x falls in

View source: R/spatial_functions.R

st_extract_withinR Documentation

Extract information from geometry that a point x falls in

Description

For each point in x, identify which geometry in y the point falls within and extract value of variable var. This is good, for example, if you have points and you want to extract information about the county/census tract/etc.

Usage

st_extract_within(x, y, var)

Arguments

x

sf object consisting of points

y

sf object consisting of geometries

var

character of variable name you wish to extract from y

Examples

library(sf)
set.seed(1)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source 
#>   `/Users/kbutts/Library/R/arm64/4.4/library/sf/shape/nc.shp' 
#>   using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> Geodetic CRS:  NAD27
x <- st_as_sf(data.frame(id = 1:10, geometry = st_sample(nc, 10)))
x$CNTY_ID = st_extract_within(x, nc, "CNTY_ID")
x
#> Simple feature collection with 10 features and 2 fields
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: -82.75835 ymin: 33.91767 xmax: -76.27089 ymax: 36.41003
#> Geodetic CRS:  NAD27
#>    id                   geometry CNTY_ID
#> 1   1 POINT (-81.96962 35.97911)    1892
#> 2   2 POINT (-81.02428 36.41003)    1827
#> 3   3 POINT (-79.24443 34.44897)    2150
#> 4   4 POINT (-76.27089 35.63616)    1963
#> 5   5 POINT (-78.46464 33.91767)    2241
#> 6   6 POINT (-78.74558 34.90677)    2090
#> 7   7 POINT (-82.75835 35.17603)    2067
#> 8   8  POINT (-78.23211 35.4945)    1989
#> 9   9 POINT (-80.91805 35.20704)    2041
#> 10 10 POINT (-79.91082 36.11566)    1903

kylebutts/kfbmisc documentation built on April 17, 2025, 5:20 p.m.