install.packages("gstat")
Source Materials
The following materials are modified from Spatial Interpolation in R.
1. Background
Spatial interpolation is a method used to estimate values at unobserved locations based on observed data from nearby points. Two of the most popular spatial interpolation methods are Inverse Distance Weighting (IDW) and ordinary/universal Kriging. Today, you will perform an IDW interpolation, which assumes Tobler’s first law of geography, which states that everything is related to everything else, but near things are more related to each other.
2. Get Started
- Create an
.Rproj
as your version controlled project for Week 10 - Create a Quarto document inside your project
- Download this data folder from Google Drive and move it inside your project
- Load all necessary packages and read spatial objects
library(tidyverse)
library(sf)
library(terra)
library(stars)
library(gstat)
library(tmap)
library(kableExtra)
<- st_read(here::here("data", "CA_Level3_Ecoregions_EPA", "ca_eco_l3.shp"))
ca_ecoregions
<- here::here("data", "wc2.1_2.5m")
bioclim_dir <- list.files(bioclim_dir, pattern = glob2rx("*.tif$"), full.names = TRUE)
bioclim <- bioclim[
bioclim_sort # Sort filepaths based on numeric suffix
order(
# Extract numeric suffix of filenames and convert to numeric
as.numeric(gsub(".*_(\\d+)\\.tif$", "\\1", bioclim)))]
<- rast(bioclim_sort)
bioclim_rast
<- c("annualMeanTemp", "meanDiurnalRange", "isothermality", "tempSeasonality", "maxTempWarmMonth", "maxTempColdMonth", "tempAnnualRange", "meanTempWetQ", "meanTempDryQ", "meanTempWarmQ", "meanTempColdQ", "annualPrecip", "precipWetMonth", "precipDryMonth", "precipSeasonality", "precipWetQ", "precipDryQ", "precipWarmQ", "precipColdQ")
variables names(bioclim_rast) <- variables
3. Your Task
Now, to meet this week’s learning objectives, your task:
- Crop and mask
bioclim_rast
withca_ecoregions
- Use
terra::spatSample
to generate random points in cropped and maskedbioclim_rast
- Hint: Set
as.points = TRUE
withinspatSample
and convert tosf
object for Step #3
- Hint: Set
- Create a grid with
sf::st_make_grid
and convert grid tostars
object withst_as_stars
- Use
gstat::idw
to perform an inverse distance weighted interpolation for a variable of interest (annualMeanTemp, meanDiurnalRange, isothermality, etc.) - Use
rast
andmask
on interpolatedstars
object from Step #4 - Find interpolated mean of the variable of interest for each ecoregion in California using
zonal
- Hint: Convert
ca_ecoregions
torast
object withrasterize
- Hint: Convert