Introduction to Spatial Data in R

Author

Mark Nepf (mnepf@uw.edu)

Published

September 22, 2026

Introduction

Spatial data are data that contain information about the location and shape of observations. Unlike ordinary tabular data (e.g., dataframes), which primarily describe what an observation is, spatial data also describe where an observation is located.

Spatial data are used across a wide range of disciplines and applications. Researchers may use spatial data to map demographic characteristics, study patterns of land use, analyze access to services, examine environmental conditions, or investigate how observations are distributed across space. In these applications, geographic location is an important part of the data itself.

Spatial data are commonly divided into two broad types: vector and raster

  • Vector data represent discrete geographic features using points, lines, and polygons. For example, points can represent individual locations, lines can represent roads or rivers, and polygons can represent areas such as neighborhoods or administrative boundaries.

  • Raster data represent geographic space as a grid of cells (pixels), with each cell containing a value. Raster data are commonly used to represent continuous phenomena such as elevation, temperature, or land cover.

In this vignette, we focus on vector spatial data and introduce the tools and concepts needed to work with them in R.

R Packages

You will need the following R packages. If you have already installed them, skip the install.packages lines.

# install
install.packages("sf")  # spatial data
install.packages("tidyverse")  # cleaning data
# load
library(sf)
library(tidyverse)

The primary package for working with vector spatial data in R is sf, developed by Pebesma & Bivand (2023) and Pebesma (2018). sf (which stands for “simple features”) provides a consistent framework for storing, manipulating, mapping, and analyzing spatial data in R. Importantly, sf objects retain the structure of a regular dataframe while adding a geometry column that describes the location and shape of each observation.

Spatial Data Types

Spatial data can represent different types of geographic features. Specifically, the geometry column inherent to spatial data contain the coordinate pairs that, in aggregate, create the spatial feature. The three most common types of spatial features are points, lines, and polygons. These different geometry types allow spatial data to describe both individual locations and geographic areas.

Points represent individual locations, such as addresses, schools, hospitals, or bus stops.

Figure 1 displays Link Light Rail stations in King County, Washington. These data are stored as points and reflect the coordinates of individual stations. Scroll through the map and click on a point to see the name of the station!

Figure 1: Link Light Rail Stations in King County, WA

Table 1 provides 10 of the station observations from Figure 1. These data are drawn directly from the raw spatial data. Notice that each observation contains a single pair of coordinates (i.e., longitude and latitude), reflecting the fact that point features are just that - a single point based on individual pairs of coordinates.

Thus, the geometry column for point features contains just one coordinate pair per observation.

Table 1:

Link Light Rail Station Coordinates

Station Name Coordinate Pair
Westlake Station -122.34, 47.61
University Street Station -122.34, 47.61
Pioneer Square Station -122.33, 47.6
International District Station -122.33, 47.6
Stadium Station -122.33, 47.59
SODO Station -122.33, 47.58
Beacon Hill Station -122.31, 47.58
Mount Baker Station -122.3, 47.58
Columbia City Station -122.29, 47.56
Othello Station -122.28, 47.54

Lines represent linear features, such as roads, rivers, transit routes, or trails.

Figure 2 displays the Link Light Rail routes associated with the stations in Figure 1. Here, data are stored as lines and reflect the paths followed by the Light Rail system.

Figure 2: Link Light Rail Routes in King County, WA

Table 2 provides 10 route observations from Figure 2. Unlike the point data in Table 1, each observation here contains many coordinate pairs. Because there are so many, Table 2 reports the number of coordinate pairs rather than the raw longitudes and latitudes. The large number of coordinate pairs reflects the structure of line features: collections of connected points that, together, represent the length and location of a line. Each turn in a Light Rail route is stored in the geometry column as multiple coordinate pairs, which collectively approximate the curve of a line. As expected, longer line features typically contain more coordinate pairs, seen in Table 2 as the positive correlation between Route Length and Coordinate Pairs.

Thus, the geometry column for line features typically contain multiple coordinate pairs per observation.

Table 2:

Link Light Rail Routes

Route Name Route Length
(miles)
Coordinate
Pairs
Central Link 13.9 3,973
Airport Link 1.7 227
Tacoma Link 1.8 411
University Link 3.2 376
Northgate Link 3.8 199
S 200th Extension 1.7 404
Lynnwood Link 8.5 2,343
Northgate Link 0.5 44
Federal Way Link 7.8 1,538
East Link 6.1 1,128

Polygons represent areas, such as states, counties, Census tracts, parks, or watersheds. Unlike points and lines, polygons reflect geographic areas with defined boundaries.

Figure 3 displays public parks in King County, Washington. These data are stored as polygons; each polygon reflects the geographic boundary of a single park. The size and shape of each polygon correspond to the actual area occupied by the park. Scroll through the map and click on a park to see its name!

Figure 3: Public Parks in King County, WA

Table 3 provides 10 park observations from Figure 3. Similar to lines, each polygon observation contains a large number of coordinates. As Park Area increases (or as the boundary becomes more complex), the number of Coordinate Pairs typically increases, as well. However, unlike lines, polygon features must represent a closed, unbroken area. To achieve this, the sequence of coordinates contained in the geomtry column for each observation forms a continuous loop, where the first and last coordinate pairs are identical, enclosing the geographic space inside.

Thus, the geometry column for polygon features contains a closed series of multiple coordinate pairs per observation to define a complete spatial area.

Table 3:

Public Parks

Park Name Park Area
(m2)
Coordinate
Pairs
Mt Baker Ridge Viewpoint 452 10
Rotary Viewpoint 9,069 62
Loyal Heights Playfield 27,042 79
Twelfth Avenue South Viewpoint 4,316 22
Urban Triangle Park 850 9
Thomas C. Wales Park 5,460 20
West Duwamish Greenbelt 113,211 559
Weather Watch Park 2,626 15
Dr. Rizal Park 38,733 97
Auburn Environmental Park 760,238 305

Coordinate Reference System

One of the most important concepts related to spatial data is the Coordinate Reference System (CRS). A dataset’s CRS tells R how coordinates correspond to locations on Earth’s surface.

While it may seem intuitive that a single pair of coordinates should point to one exact spot on Earth, the reality is that Earth is an irregular, bumpy ellipsoid, slightly squashed at the poles and bulging at the equator. Because of this, working directly with coordinates on Earth’s curved surface can make certain spatial calculations more complicated, particularly when calculating distances and areas.

As a workaround, mathematicians have created different models to approximate Earth’s surface. These models, referred to as datums, define the shape and position of the Earth so that mapping and spatial analysis becomes possible. A datum is the foundation for a CRS - each CRS uses a specific datum when defining its spatial reference, and every pair of coordinates is entirely dependent on that underlying datum. If two datasets use different datums, the exact same numerical coordinates can point to different locations in the real world, sometimes by hundreds of meters. Thus, choosing an appropriate CRS is especially important when the goal is spatial analysis.

click here for more information on Coordinate Reference Systems

Within the concept of Coordinate Reference Systems, there are two broad categories: Geographic Coordinate Systems (GCS) and Projected Coordinate Systems (PCS). The choice between these systems drastically affects how distances, areas, and other spatial measurements are calculated.

Geographic Coordinate Systems

GCS maintains Earth’s three-dimensional, roughly spherical shape. Locations are represented using angular units like longitude and latitude (i.e., degrees). Because GCS closely represents the shape of Earth, it is preferable when the spatial data goal is global. For instance, if you are plotting all major global airports, GCS would be preferable because it provides you with a standard way to say, “this airport is at this exact latitude and longitude on the globe.”

However, GCS becomes problematic when attempting to run spatial analyses, such as distance calculations, precisely because the Earth curves. The physical distance of one degree of longitude shrinks from about 111 kilometers at the equator to zero at the poles. You cannot measure distance or area directly using latitude and longitude degrees because the distance represented by a degree changes depending on where you are on Earth. Hence, depending on where your data are located and what type of measurement you are performing, GCS-based spatial estimates can be quite problematic.

Projected Coordinate Systems

PCS, on the other hand, flattens Earth’s curved surface onto a two-dimensional grid using linear units like meters or feet. By flattening the surface, spatial analyses can become more reliable, particularly when the projection is designed for the geographic area and type of analysis being performed. PCS is often appropriate when working with local or regional spatial data, such as a city, state, or county, because a carefully chosen projection can minimize distortion over that area. Additionally, by flattening the surface, the irregularity of one degree of longitude is no longer a problem.

For instance, suppose you are calculating the total area of a city’s parks to determine funding, or measuring the distance of routes for emergency vehicles in a county. A suitable PCS can be better in these scenarios because the projection can be designed to minimize the types of distortion that matter for your analysis. Now, you can run your area and distance calculations using coordinates expressed in simple units such as meters or feet.

At larger scales (e.g., continents or the entire globe), however, it is mathematically impossible to flatten a curved surface without introducing some type of distortion. The classic example is trying to flatten an intact orange peel without ripping, stretching, or compressing it. Consequently, while PCS is not necessarily inappropriate for larger areas, the choice of projection becomes increasingly important. Different projections are designed to preserve different properties, such as area, distance, shape, or direction. For example, an equal-area projection may be appropriate when comparing the areas of regions across a continent, while an equidistant projection may be more appropriate when accurate distances are the primary concern.

TIP

The choice between GCS and PCS should not simply be based on whether the data are global or local. Consider the geographic extent of your data and, most importantly, what spatial property you need to preserve. GCS provides a consistent way to represent locations on Earth’s surface, while PCS transforms those locations onto a flat surface in a way that can make certain spatial analyses more appropriate and accurate.

TIP

Choosing an appropriate CRS is an important but location- and analysis-dependent step. Moreover, there are thousands of different CRS definitions used around the world. If you are unsure which to use, you can search for an appropriate CRS at epsg.io or spatialreference.org by entering your location or projection name.

Spatial Data Files

So far, we have focused on what spatial data represent: geographic features such as points, lines, and polygons, together with attributes describing those features. Spatial data also contain Coordinate Reference Systems to tell R how the geographic coordinates relate to locations on Earth’s surface. It is also important to be aware of the different file formats that can contain spatial data.

A spatial dataset is not synonymous with a particular file format. Spatial data can be stored in several different formats, just as ordinary tabular data can be stored as .csv files or .xlsx spreadsheets. Some common formats for storing spatial data include:

  • Shapefile (.shp) - a widely used and relatively simple format for storing vector spatial data. Despite being commonly referred to as a single “shapefile,” a shapefile actually consists of multiple files that work together. The .shp file stores the geometry, while other files store information such as attribute data and the coordinate reference system.

  • GeoPackage (.gpkg) - a newer, open format that can store multiple spatial layers, along with their attributes and other information, in a single file.

  • GeoJSON (.geojson) - a text-based format commonly used for exchanging geographic data, particularly for web mapping and data sharing.

  • File Geodatabase (.gdb) - a format developed by the Environmental Systems Research Institute (“Esri”) that can contain multiple spatial datasets and other types of geographic information within a single geodatabase.

Although these formats store spatial data in different ways, they generally represent the same basic types of geographic features. For example, the King County spatial data plotted in Figure 1, Figure 2, and Figure 3 could be stored as a Shapefile, GeoPackage, GeoJSON, or File Geodatabase. The steps used to load the data into R may differ depending on the format, but once the data have been loaded into an sf object, we can work with them in the same way.

Thus, spatial data file formats affect how the data are stored but do not change the basic structure of the spatial data once they are loaded into R. Put another way, spatial data are the actual data, while a Shapefile, GeoPackage, GeoJSON file, or File Geodatabase are just different ways of storing those data.

In R, the sf package provides a common framework for working with spatial data from many different file formats. This means that we do not need to learn the technical details of every format before we can work with spatial data. Instead, we can use functions such as read_sf to read spatial data into an sf object. Once the data are in an sf object, we can use the same sf functions to inspect, manipulate, and map the data, regardless of the format they originally came from.

Importantly, some files can contain multiple spatial datasets, called layers. For example, a Shapefile might contain separate layers for roads, parks, and transit stops. When a file contains multiple layers, we need to specify which layer we want to load into R.

Loading Spatial Data

To illustrate how to import spatial data into R, we will use the public parks data plotted in Figure 3. These data are made publicly available by the King County Geographic Information Systems Center and can be accessed here: Parks in King County (select Download and then Shapefile Download). Once downloaded, unzip the file and store it in your project folder.

The sf package makes loading spatial data into R simple. We will use the read_sf function, which is compatible with any spatial feature (e.g., points, lines, polygons). read_sf requires two arguments:

  1. The location of the spatial data on your computer
  2. The name of the layer you want from that spatial data

The latter reflects the fact that spatial data can contain many layers. We can confirm the layer’s name using st_layers, which prints the names of all layers present in the spatial data.

st_layers("data/parks/area/Parks_in_King_County___park_area.shp")$name
[1] "Parks_in_King_County___park_area"

Here, we see these spatial data contain only one layer named Parks_in_King_County___park_area. This name can be input directly into read_sf:

# load King County parks
parks <- read_sf("data/parks/area/Parks_in_King_County___park_area.shp",  # spatial data location
                 "Parks_in_King_County___park_area")  # layer name
CAUTION

Layer names will not always match the file names of spatial data. Especially in cases where multiple layers exist, the names of some layers will inevitably be different from the spatial data’s file name. Additionally, layer names can change depending on changes made by the host/provider of the spatial data. It is therefore good to confirm that you have the correct layer name when working with spatial data.

Opening parks (run View, as below, or double-click on parks in the Data Environment) demonstrates that sf objects contain all the common attribute data one would expect in a dataframe, with the addition of a geometry column. This column contains the spatial information associated with each observation, allowing us to map and analyze the King County’s public parks based on their location and shape. Because sf objects retain both attribute and spatial information, we can use familiar tidyverse and ggplot functions to manipulate and visualize the data, while also taking advantage of sf functions to perform spatial operations.

View(parks)