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")
= terra::extract(srtm, zion_points)
elevation = cbind(zion_points, elevation)
zion_points_elev
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:
= cbind(c(-113.2, -112.9), c(37.45, 37.2)) |>
zion_transect ::st_linestring() |>
sf::st_sfc(crs = crs(srtm)) |>
sf::st_sf(geometry = _ ) # <- fancy new place holder
sf
plot(srtm_masked, col = grDevices::terrain.colors(50))
plot(zion_transect, add = TRUE, lwd = 3)
The we are using points on this line:
$id = 1:nrow(zion_transect) # just on transect
zion_transect= st_segmentize(zion_transect, dfMaxLength = 250) # I am curious why I get 257 pts
zion_transect # we are casting as POINT
= st_cast(zion_transect, "POINT") zion_transect
## 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])
= terra::extract(srtm, zion_transect)
zion_elev # just cbind
= cbind(zion_transect, zion_elev)
zion_transect # quick plot
plot(zion_transect$dist, zion_transect$srtm, type = "l")
6.4.3 Extracting value on polygons
= terra::extract(x = srtm, y = zion)
zion_srtm_values 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:
= rast(system.file("raster/nlcd.tif", package = "spDataLarge"))
nlcd = st_transform(zion, st_crs(nlcd))
zion2 = terra::extract(nlcd, zion2)
zion_nlcd |>
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