Prerequsites
library(sf)
## Linking to GEOS 3.10.2, GDAL 3.4.1, PROJ 7.2.1; sf_use_s2() is TRUE
library(tidyverse)
## -- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --
## v dplyr 1.1.2 v readr 2.1.4
## v forcats 1.0.0 v stringr 1.5.0
## v ggplot2 3.4.3 v tibble 3.2.1
## v lubridate 1.9.2 v tidyr 1.3.0
## v purrr 1.0.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(terra)
## terra 1.7.29
##
## Attaching package: 'terra'
##
## The following object is masked from 'package:tidyr':
##
## extract
# practice filtering a raster
elev <- rast(nrows = 6, ncols = 6, resolution = 0.5,
xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5,
vals = 1:36)
plot(elev)
# set all cells to NA based on condition
elev[elev < 20] <- NA
plot(elev)
# let's practice combining (or unioning) geometries
# read in shapefile of the counties of North Carolina
nc = st_read(system.file("shape/nc.shp", package="sf"))
## Reading layer `nc' from data source
## `C:\Users\acaug\Documents\R\win-library\4.1\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
plot(nc["AREA"])
# combines all geometries without resolving borders
nc_combine <- st_combine(nc)
plot(nc_combine)
# finds the union of all geometries
nc_union <- st_union(nc)
plot(nc_union)
# let's exploring removing geometries
# pick a few counties to remove
counties <- nc %>%
filter(NAME %in% c("Ashe", "Alleghany", "Surry")) %>%
st_union()
# plot counties on top of the unioned version of NC
ggplot() +
geom_sf(data = nc_union, fill = "grey", color = "transparent") +
geom_sf(data = counties, fill = "black", color = "transparent")
# create a new geometry that is the difference between the unioned version of NC and the counties
nc_difference <- st_difference(nc_union, counties)
# plot the difference on top of the unioned version of NC
# counties should be missing!
ggplot() +
geom_sf(data = nc_union, fill = "grey", color = "transparent") +
geom_sf(data = nc_difference, fill = "black", color = "transparent")