6.4 Raster extraction

We want to extract values from “target” based on a selector (lot of time a vector). The result will depend on the type of object (point, lines, polygons) we are using to select.

6.4.1 Extracting value on points

data("zion_points", package = "spDataLarge")
elevation = terra::extract(srtm, zion_points)
zion_points_elev = cbind(zion_points, elevation)

plot(srtm_masked, col = grDevices::terrain.colors(50))
plot(zion_points, add = TRUE, pch = 16)

6.4.2 Extracting value on lines

First we create a line:

zion_transect = cbind(c(-113.2, -112.9), c(37.45, 37.2)) |>
  sf::st_linestring() |> 
  sf::st_sfc(crs = crs(srtm)) |>
  sf::st_sf(geometry = _ ) # <- fancy new place holder

plot(srtm_masked, col = grDevices::terrain.colors(50))
plot(zion_transect, add = TRUE, lwd = 3)

The we are using points on this line:

zion_transect$id = 1:nrow(zion_transect) # just on transect
zion_transect = st_segmentize(zion_transect, dfMaxLength = 250) # I am curious why I get 257 pts
# we are casting as POINT
zion_transect = st_cast(zion_transect, "POINT")
## Warning in st_cast.sf(zion_transect, "POINT"): repeating attributes for all
## sub-geometries for which they may not be constant

I am not sure we need the group_by() ?

zion_transect = zion_transect |> 
  #group_by(id) |> 
  mutate(dist = st_distance(geometry)[, 1]) 
zion_elev = terra::extract(srtm, zion_transect)
# just cbind 
zion_transect = cbind(zion_transect, zion_elev)
# quick plot
plot(zion_transect$dist, zion_transect$srtm, type = "l")

6.4.3 Extracting value on polygons

zion_srtm_values = terra::extract(x = srtm, y = zion)
dim(zion_srtm_values)
## [1] 88080     2

6.4.4 With quantitative data:

group_by(zion_srtm_values, ID) |> 
  summarize(across(srtm, list(min = min, mean = mean, max = max)))
## # A tibble: 1 × 4
##      ID srtm_min srtm_mean srtm_max
##   <dbl>    <int>     <dbl>    <int>
## 1     1     1122     1818.     2661

6.4.5 With qualitative data:

nlcd = rast(system.file("raster/nlcd.tif", package = "spDataLarge"))
zion2 = st_transform(zion, st_crs(nlcd))
zion_nlcd = terra::extract(nlcd, zion2)
zion_nlcd |> 
  group_by(ID, levels) |>
  count()
## # A tibble: 7 × 3
## # Groups:   ID, levels [7]
##      ID levels          n
##   <dbl> <fct>       <int>
## 1     1 Developed    4205
## 2     1 Barren      98285
## 3     1 Forest     298299
## 4     1 Shrubland  203700
## 5     1 Herbaceous    235
## 6     1 Cultivated     62
## 7     1 Wetlands      679

Important! If you are using a lot of polygons you should use exactextract