⌛ 25 minutes

image.png

<aside> 💡

In this practical, you will make your first maps in R and learn the two packages almost every spatial analysis in R relies on:

  1. Read, inspect, subset and map vector data (points and polygons) with sf
  2. Read, crop, mask and aggregate raster data with terra
  3. Combine the two: count points in polygons, and extract raster values for points and polygons </aside>

Your route through the 25 minutes


This is the first of five practicals in a 2-hour session. There are seven stations, numbered 0 to 6. Use the times in the table to keep on track. Tasks marked + optional can be skipped if you are short of time.

Station Minutes What you do You leave with
0 Set up 0–3 Project folder, packages A session that runs
1 Meet sf 3–7 Read, inspect and subset the Wytham Woods stands A ww object you understand
2 Map it 7–11 Base plots, then a ggplot2 map and an area choropleth A publication-style map
3 Points in polygons 11–15 Turn a CSV into points, count oaks per stand A map of oaks per stand
4 Meet terra 15–18 Read and inspect the WorldClim temperature raster An annual mean temperature layer
5 Crop, mask, aggregate 18–22 Clip the raster to the UK and coarsen it A UK-only raster at several resolutions
6 Raster meets vector 22–25 Extract values at points and summarise by polygon Mean temperature for every UK district

Station 0 · Set up


⏱️ 0–3 min

<aside> 📥

Download

spatial.zip

</aside>

Unzip the spatial.zip in your favourite workspace. Inside spatial/ you have a ww/ folder containing ww.shp, ww.shx, ww.dbf and ww.prj. Also there are oaks.csv and tavg.tif, prec.tif, srad.tif, and wind.tif. In RStudio, go to File → New Project → Existing Directory and choose the spatial/.

# ---- 1. Where am I? ----
getwd()          # should end in /spatial
list.files()     # should list ww, oaks.csv and tavg.tif

# ---- 2. Packages: install once, then load every session ----
install.packages(c("sf", "terra", "ggplot2", "dplyr", "units", "rnaturalearth"))
# ne_states() also needs a high-resolution data package that is NOT on CRAN:
install.packages("rnaturalearthhires", repos = "https://ropensci.r-universe.dev")

library(sf)             # vector data ("simple features")
library(terra)          # raster data (successor to the older raster package)
library(ggplot2)        # plotting; geom_sf() draws sf objects
library(dplyr)          # mutate() and friends
library(units)          # drop_units()
library(rnaturalearth)  # country and state boundaries

<aside> ✅

EXPECT TO SEE

No red error messages. Loading sf prints the versions of GEOS, GDAL and PROJ it links to; that is normal. If a package will not install, ask for help now rather than later.

</aside>

<aside> 🎉

MILESTONE!

You have a project folder that R can find, and the two core spatial packages, sf and terra, are loaded.

</aside>

Station 1 · Meet sf: the Wytham Woods stands


⏱️ 3–7 min