10 Spatial Analysis

10.1 Packages

These days, the recommendation is to use sf (instead of sp) and terra (instead of raster). The sf package is great and should no doubt be used instead of sp. It drops easily into ggplot2 and other packages. terra may need to be converted to a raster for compatibility with some packages or functions.

10.1.1 sf

10.1.2 terra

10.1.3 raster

10.1.3.1 Cropping a raster

To crop a raster to the extent of relocations:

## Packages
library(data.table)
library(raster)
library(rasterVis)
library(ggplot2)

## Load data
# DT is a data.table
load('data/DT.rda')

# DEM is a raster
load('data/dem.rda')

## Plot
# Plot raster and points
gplot(dem) +
    geom_tile(aes(fill = value)) +
    geom_point(aes(X, Y), data = DT)


## Crop to points
cropped <- crop(dem, DT[, as.matrix(cbind(X, Y))])

gplot(cropped) +
    geom_tile(aes(fill = value)) +
    geom_point(aes(X, Y), data = DT)

If you’d like to buffer the points first, use sf.

## Optionally buffer points first
library(sf)

pts <- st_as_sf(DT, coords = c('X', 'Y'))


buf <- st_buffer(pts, 1e4)


bufCropped <- crop(dem, buf)

gplot(bufCropped) +
    geom_tile(aes(fill = value)) +
    geom_point(aes(X, Y), data = DT)

10.2 Spatial data

Open sources: Open Street Map, Natural Earth, Canadian Government, Provincial Governments.

Examples of downloading and preparing spatial data from these sources in the study-area-figures repository (*-prep.R scripts). Packages used for downloading data include: osmdata, rnaturalearth and curl.

Recently from rOpenSci, Dilinie Seimon, Varsha Ujjinni Vijay Kumar highlighted many collections of open spatial data, from land cover to administrative boundaries and air pollution to malaria: https://rspatialdata.github.io/, https://ropensci.org/blog/2021/09/28/rspatialdata/

10.3 Distance to

Calculating distance to something, eg. distance from moose relocations to the nearest road, using Alec’s distanceto package.

It can be installed with the following code

install.packages('distanceto', repos = 'https://robitalec.r-universe.dev')
library(distanceto)
library(sf)

points <- st_read('some-point.gpkg')
lakes <- st_read('nice-lakes.gpkg')

distance_to(points, lakes)

Here are the docs: https://robitalec.github.io/distance-to/