library(tidyverse)
library(sf)
library(terra)
library(spData)
library(spDataLarge)
# Load raster data representing grain sizes with the three classes clay, silt and sand
<- terra::rast(system.file("raster/grain.tif", package = "spData")) grain
Subset Points in New Zealand/Aotearoa
# Subset New Zealand elevation points to > 3100 meters
<- nz_height %>%
nz_height3100 ::filter(elevation > 3100)
dplyr
# Create template: define the extent, resolution, and CRS based on nz_height3100
<- rast(terra::ext(nz_height3100),
nz_template resolution = 3000,
crs = terra::crs(nz_height3100))
Count Points in Each Grid Cell
# Convert vector points to raster data
# Function "length" returns a count of the elevation points per cell
<- rasterize(nz_height3100, nz_template, field = "elevation", fun = "length")
nz_raster
plot(nz_raster, main = "Number of Elevation Points > 3100 in Each Grid Cell")
plot(st_geometry(nz_height3100), add = TRUE)
Find Maximum Elevation in Each Grid Cell
# function "max" returns maximum elevation value per cell
<- rasterize(nz_height3100, nz_template, field = "elevation", fun = max)
nz_raster2
plot(nz_raster2, main = "Maximum Elevation in Each Grid Cell ")
plot(st_geometry(nz_height3100), add = TRUE)
Aggregate and Resample Raster
# Reduce the resolution by combining 2 cells in each direction into larger cells
# Sum the values of all cells for the resulting elevation value
<- aggregate(nz_raster, fact = 2, fun = sum, na.rm = TRUE)
nz_raster_low
# Convert the new raster's resolution back to the 3kmx3km resolution of original raster
<- resample(nz_raster_low, nz_raster)
nz_resample
<- c(nz_raster, nz_resample)
plots <- c("Original 6 x 6 km", "Resample 6 x 6 km")
labs plot(plots, main = labs)
plot(nz_raster_low, main = "Resample 3 x 3 km")
Vectorize Raster
# Convert raster data to polygon vector data
<- as.polygons(grain) %>%
grain_poly st_as_sf()
plot(grain, main = "Grain (Raster)")
plot(grain_poly, main = "Grain (Vector)")
# Subset polygons to only clay
<- grain_poly %>%
clay ::filter(grain == "clay")
dplyr
plot(clay, main = "Clay")