Here, we present an application of spatial interpolation frequently used in geostatistics. We exclusively use software from the CRAN library in R. We will go into detail in forthcoming texts.
suppressWarnings(suppressPackageStartupMessages(library(sf)))
suppressWarnings(suppressPackageStartupMessages(library(stars)))
suppressWarnings(suppressPackageStartupMessages(library(gstat)))
suppressWarnings(suppressPackageStartupMessages(library(tigris)))
suppressWarnings(suppressPackageStartupMessages(library(viridis)))
suppressWarnings(suppressPackageStartupMessages(library(gridExtra)))
suppressWarnings(suppressPackageStartupMessages(library(ggplot2)))
The sf library, in particular the st_as_sf() command, is needed to convert data into sf format. An sf object is a standard R data frame or tibble, but it also includes data (usually named geometry) that stores the spatial shapes for each observation.
The stars library is used to create a spatial grid determining the points where measurements are interpolated.
The gstat package is a library for geostatistical modeling, prediction, and simulation. We use the function idw for Inverse Distance Weighting (IDW).
The tigris library provides U.S. Census Bureau cartographic boundary shapefiles as simple feature (sf) objects. The states function is used to get county boundaries in a part of California below.
The viridis library offers a collection of nice color maps to improve visualisation of data.
The gridExtra library allows working with grid graphics (side-by-side graphs).
stations <- read.csv2("stations.csv", sep = ",")
colnames(stations)
## [1] "ID" "Station.Name" "River.Basin" "County"
## [5] "Longitude" "Latitude" "ElevationFeet" "Operator"
## [9] "Map"
precip <- read.csv2("sfba_precip.csv", sep =",")
colnames(precip)
## [1] "STATION_ID" "DURATION" "SENSOR_NUMBER" "SENSOR_TYPE"
## [5] "DATE.TIME" "OBS.DATE" "VALUE" "DATA_FLAG"
## [9] "UNITS"
If we want the coordinates and the precipitation data in one file, we have to merge the files. We can probably use stations$ID and precip$STATION_ID as columns to merge on. The intersect command gives us the stations having both the coordinates and the precipitation data:
intersect(stations$ID, precip$STATION_ID)
## [1] "BKD" "BNE" "CAD" "HKY" "LAH" "LSG" "LSW" "LTR" "MLR" "ONO" "OSO" "POV"
## [13] "PUL" "RSP" "STA" "SVA" "WRS"
We merge both datasets on the columns mentioned above:
rain = merge(stations, precip, by.x = "ID", by.y = "STATION_ID")
dim(rain)
## [1] 12665 17
As an option, we reduce the file to the minimum needed for the IDW (but we keep ID as an extra column):
rain = rain[, c(1, 5, 6, 15)]
colnames(rain)[4] = "rain"
colnames(rain)
## [1] "ID" "Longitude" "Latitude" "rain"
We check the data types of the columns of the frame:
sapply(rain, class)
## ID Longitude Latitude rain
## "character" "character" "character" "character"
We have to change columns 2 to 4 to numeric:
for (i in 2:4) {
rain[,i] = as.numeric(rain[,i])
}
## Warning: NAs introduced by coercion
sapply(rain, class)
## ID Longitude Latitude rain
## "character" "numeric" "numeric" "numeric"
Finally, incomplete rows are being removed (because we have seen the warning above):
sum(is.na(rain$rain))
## [1] 12
rain = rain[complete.cases(rain),]
str(rain)
## 'data.frame': 12653 obs. of 4 variables:
## $ ID : chr "BKD" "BKD" "BKD" "BKD" ...
## $ Longitude: num -122 -122 -122 -122 -122 ...
## $ Latitude : num 38 38 38 38 38 ...
## $ rain : num 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 ...
head(rain)
## ID Longitude Latitude rain
## 1 BKD -121.884 37.95 5.12
## 2 BKD -121.884 37.95 5.12
## 3 BKD -121.884 37.95 5.12
## 4 BKD -121.884 37.95 5.12
## 5 BKD -121.884 37.95 5.12
## 6 BKD -121.884 37.95 5.12
So the data frame rain contains the precipitation measurements and the corresponding coordinates in degrees.
As an option, we could save this file (does not work in case the file is open !):
# write.csv(rain, file = "rain.csv")
# rain <- read.csv(file = "rain.csv", header = T, row.names = 1) # retrieve the data
The simple feature format provides a standard for geographic vector data representation. The format is mandatory when working with geostatistical modeling. We transform our data frame to sf format using the command st_as_sf of the sf package:
rain.sf <- st_as_sf(rain, coords = c("Longitude", "Latitude"), crs = 4326)
str(rain.sf)
## Classes 'sf' and 'data.frame': 12653 obs. of 3 variables:
## $ ID : chr "BKD" "BKD" "BKD" "BKD" ...
## $ rain : num 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 ...
## $ geometry:sfc_POINT of length 12653; first list element: 'XY' num -122 38
## - attr(*, "sf_column")= chr "geometry"
## - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA
## ..- attr(*, "names")= chr [1:2] "ID" "rain"
rain.sf$geometry
## Geometry set for 12653 features
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -123.01 ymin: 37.2068 xmax: -121.736 ymax: 38.727
## Geodetic CRS: WGS 84
## First 5 geometries:
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
The geometry slot includes the coordinates of the data set in degrees. Longitudes 126°W to 120°W cover the Bay Area, Sacramento, the Northern Coast, much of the Central Valley and most of Northern California. For this area, the Coordinate Reference System (CRS) 4326 is the right choice.
Note: The rain.sf is an object of class sf to which many functions can be applied. A listing of these functions can be listed using the methods function (large output hidden):
methods(class = class(rain.sf))
The function st_transform converts the coordinates of an sf object from one coordinate reference system (CRS) to another. Further explanations regarding CRS can be found on this site.
Above, we have already assigned a CRS to the input. This can be checked with st_crs:
st_crs(rain.sf)$input # only input slot displayed
## [1] "EPSG:4326"
By applying st_transform we obtain a projected coordinate reference system (CRS) displaying distances and areas in meters rather than in degrees.
For the transformation, we choose the metric CRS EPSG:26910. This corresponds to the NAD83 / UTM zone 10N, in meters. Zone 10 covers longitudes 126°W to 120°W, so it works well for:
rain.utm <- st_transform(rain.sf, 26910)
str(rain.utm)
## Classes 'sf' and 'data.frame': 12653 obs. of 3 variables:
## $ ID : chr "BKD" "BKD" "BKD" "BKD" ...
## $ rain : num 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 5.12 ...
## $ geometry:sfc_POINT of length 12653; first list element: 'XY' num 598050 4200855
## - attr(*, "sf_column")= chr "geometry"
## - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA
## ..- attr(*, "names")= chr [1:2] "ID" "rain"
UTM stands for Universal Transverse Mercator (a map projection system that divides the Earth into 60 north-south zones).
We confirm that the rain.utm contains coordinates in meters, in contrast to rain.sf which measures in degrees:
rain.sf$geometry
## Geometry set for 12653 features
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: -123.01 ymin: 37.2068 xmax: -121.736 ymax: 38.727
## Geodetic CRS: WGS 84
## First 5 geometries:
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
## POINT (-121.884 37.95)
rain.utm$geometry
## Geometry set for 12653 features
## Geometry type: POINT
## Dimension: XY
## Bounding box: xmin: 499130.7 ymin: 4118337 xmax: 611724.4 ymax: 4286494
## Projected CRS: NAD83 / UTM zone 10N
## First 5 geometries:
## POINT (598049.8 4200855)
## POINT (598049.8 4200855)
## POINT (598049.8 4200855)
## POINT (598049.8 4200855)
## POINT (598049.8 4200855)
For completeness, we demonstrate how the CRS has been changed when transforming rain.sf to rain.utm:
st_crs(rain.sf)$epsg # before
## [1] 4326
st_crs(rain.utm)$epsg # after
## [1] 26910
If the tranformation was correct, we should roughly see x ≈ 596,000 and y ≈ 4,200,000 (meters) in the UTM object:
st_coordinates(rain.utm)[1, ]
## X Y
## 598049.8 4200854.7
We interpolate in an area defined by the coordinates included in
rain.utm.
We create a box in this region, and determine the resolution \(dx\) and \(dy\) (in meters):
bb <- st_bbox(rain.utm)
bb
## xmin ymin xmax ymax
## 499130.7 4118337.2 611724.4 4286494.3
We restrict predictions to the area within the stations (not outside) by defining a convex hull:
hull <- st_convex_hull(st_union(rain.utm))
out <- st_as_stars(bb, dx = 1000, dy = 1000)
rain.grd <- st_crop(out, hull)
rain.grd
## stars object with 2 dimensions and 1 attribute
## attribute(s):
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## values 0 0 0 0 0 0 11224
## dimension(s):
## from to offset delta refsys x/y
## x 1 113 499131 1000 NAD83 / UTM zone 10N [x]
## y 1 169 4286494 -1000 NAD83 / UTM zone 10N [y]
This creates a grid of \(1 \, km^2\) cells.
Remember the name of the variable:
colnames(rain.sf)
## [1] "ID" "rain" "geometry"
We try out a number of different power parameters for the IDW.
As an option, we can add a boundary layer, such as California counties, for context. This requires the tigris package (or any other shapefile):
out = counties("CA", cb = TRUE, progress_bar = FALSE)
## Retrieving data for the year 2025
counties = st_transform(out, 26910)
We will use counties in the ggplot commands below.
power = 1.0
idw.res = gstat::idw(rain ~ 1, rain.utm, rain.grd, idp = power)
## [inverse distance weighted interpolation]
We prepare a plot and save it to a variable p1. We will print it below.
p1 <- ggplot() +
geom_stars(data = idw.res, aes(fill = var1.pred)) +
geom_sf(data = counties, fill = NA, color = "grey30", linewidth = 0.3) +
geom_sf(data = rain.utm, size = 0.8) +
scale_fill_viridis_c(option = "plasma", na.value = "transparent",
name = "Rainfall (mm)") +
coord_sf(xlim = st_bbox(idw.res)[c("xmin", "xmax")],
ylim = st_bbox(idw.res)[c("ymin", "ymax")]) +
xlab(NULL) + ylab(NULL) +
scale_x_continuous(guide = guide_axis(check.overlap = TRUE)) +
theme_minimal()
power = 2.0
idw.res = gstat::idw(rain ~ 1, rain.utm, rain.grd, idp = power)
## [inverse distance weighted interpolation]
We prepare a plot and save it to a variable p2. We will print it below.
p2 <- ggplot() +
geom_stars(data = idw.res, aes(fill = var1.pred)) +
geom_sf(data = counties, fill = NA, color = "grey30", linewidth = 0.3) +
geom_sf(data = rain.utm, size = 0.8) +
scale_fill_viridis_c(option = "plasma", na.value = "transparent",
name = "Rainfall (mm)") +
coord_sf(xlim = st_bbox(idw.res)[c("xmin", "xmax")],
ylim = st_bbox(idw.res)[c("ymin", "ymax")]) +
xlab(NULL) + ylab(NULL) +
scale_x_continuous(guide = guide_axis(check.overlap = TRUE)) +
theme_minimal()
This power parameter is the one mostly applied. Let’s have a look:
p2
power = 3.0
idw.res = gstat::idw(rain ~ 1, rain.utm, rain.grd, idp = power)
## [inverse distance weighted interpolation]
We prepare a plot and save it to a variable p3. We will print it below.
p3 <- ggplot() +
geom_stars(data = idw.res, aes(fill = var1.pred)) +
geom_sf(data = counties, fill = NA, color = "grey30", linewidth = 0.3) +
geom_sf(data = rain.utm, size = 0.8) +
scale_fill_viridis_c(option = "plasma", na.value = "transparent",
name = "Rainfall (mm)") +
coord_sf(xlim = st_bbox(idw.res)[c("xmin", "xmax")],
ylim = st_bbox(idw.res)[c("ymin", "ymax")]) +
xlab(NULL) + ylab(NULL) +
scale_x_continuous(guide = guide_axis(check.overlap = TRUE)) +
theme_minimal()
power = 4.0
idw.res = gstat::idw(rain ~ 1, rain.utm, rain.grd, idp = power)
## [inverse distance weighted interpolation]
We prepare a plot and save it to a variable p4. We will print it below.
p4 <- ggplot() +
geom_stars(data = idw.res, aes(fill = var1.pred)) +
geom_sf(data = counties, fill = NA, color = "grey30", linewidth = 0.3) +
geom_sf(data = rain.utm, size = 0.8) +
scale_fill_viridis_c(option = "plasma", na.value = "transparent",
name = "Rainfall (mm)") +
coord_sf(xlim = st_bbox(idw.res)[c("xmin", "xmax")],
ylim = st_bbox(idw.res)[c("ymin", "ymax")]) +
xlab(NULL) + ylab(NULL) +
scale_x_continuous(guide = guide_axis(check.overlap = TRUE)) +
theme_minimal()
We plot the figures together using the gridExtra package:
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
Mail to UM