7.2 Example: North Carolina

# reading in an sf object
nc <- st_read(system.file("gpkg/nc.gpkg", package = "sf"))
## Reading layer `nc.gpkg' from data source 
##   `/home/runner/work/_temp/Library/sf/gpkg/nc.gpkg' using driver `GPKG'
## 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

7.2.1 Subsetting

nc[2:5, 3:7] #records 2-5 and columns 3-7 
subset of North Carolina
subset of North Carolina
Code
nc5 <- nc[1:5, ]
nc7 <- nc[1:7, ]
plot(st_geometry(nc7))
plot(st_geometry(nc5), add = TRUE, border = "brown")
cc = st_coordinates(st_centroid(st_geometry(nc7)))
text(cc, labels = 1:nrow(nc7), col = "blue")
  • the drop argument is by default FALSE meaning that the geometry column is always selected
  • selection with a spatial (sf, sfc, or sfg) object as first argument leads to selection of the features that spatially intersect with that object
(i <- st_intersects(nc5, nc7))
## Sparse geometry binary predicate list of length 5, where the predicate
## was `intersects'
##  1: 1, 2
##  2: 1, 2, 3
##  3: 2, 3
##  4: 4, 7
##  5: 5, 6
as.matrix(i)
##       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]
## [1,]  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
## [2,]  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
## [3,] FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE
## [4,] FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE
## [5,] FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
# The object i is of class sgbp (sparse geometrical binary predicate)
class(i)
## [1] "sgbp" "list"
methods(class = "sgbp")
##  [1] as.data.frame as.matrix     coerce        dim           initialize   
##  [6] Ops           print         show          slotsFromS3   t            
## see '?methods' for accessing help and source code