Reading Spatial Data in R

HES 505 Fall 2024: Session 4

Carolyn Koehn

Objectives

  1. Revisit the components of spatial data

  2. Describe some of the key considerations for thinking about spatial data

  3. Introduce the two primary R packages for spatial workflows

  4. Learn to read and explore spatial objects in R

Questions from Monday

  • Why do we need a projection for calculations on a computer?
  • What does it mean that a raster’s geometry is implicit?

Reviewing Spatial Data

Let’s Kahoot!

https://create.kahoot.it/share/isdr-session-4/888711f4-50a3-4732-a707-cbf68d9ae9dc

Mapping Location in R

Data Types and R Packages

Data Types

  • Vector Data
    • Point features
    • Line features
    • Area features (polygons)
  • Raster Data
    • Spatially continuous field
    • Based on pixels (not points)

Reading in Spatial Data: spreadsheets

  • Most basic form of spatial data

  • Need x (longitude) and y (latitude) as columns

  • Need to know your CRS

  • read_*** necessary to bring in the data

library(tidyverse)
library(sf)

file.to.read <- read_csv(file = "path/to/your/file", 
                         col_names = TRUE, col_types = NULL, 
                         na =na = c("", "NA"))

file.as.sf <- st_as_sf(file.to.read, 
                       coords = c("longitude", "latitude"), 
                       crs=4326)

Reading in Spatial Data: shapefiles

  • ALL FILES NEED TO BE IN THE SAME FOLDER
  • .shp is the shapefile itself
  • .prj contains the CRS information
  • .dbf contains the attributes
  • .shx contains the indices for matching attributes to geometries
  • other extensions contain metadata
  • st_read and read_sf in the sf package will read shapefiles into R

  • read_sf leaves character vectors alone (often beneficial)

  • st_read can handle other datatypes (like geodatabases)

  • Returns slightly different classes

Reading in Spatial Data: shapefiles

library(sf)
shapefile.inR <- read_sf(dsn = "path/to/file.shp")

Reading in Spatial Data: rasters

  • rast will read rasters using the terra package

  • Also used to create rasters from scratch

  • Returns SpatRaster object

library(terra)
raster.inR <- rast(x = "path/to/file.tif", 
                         lyrs=NULL)

Introducing the Data

  • Good idea to get to know your data before manipulating it

  • str, summary, nrow, ncol are good places to start

  • st_crs (for sf class objects) and crs (for SpatRaster objects)

  • We’ll practice a few of these now…

Saving your data

  • write_sf for sf objects; writeRaster for SpatRasters
library(sf)
library(terra)

write_sf(object = object.to.save, dsn = "path/to/save/object", append = FALSE)
writeRaster(x=object, filename = "path/to/save")