0Pricing
R Academy · Lesson

Spatial Joins and Operations

Apply st_join(), st_intersection(), st_buffer(), and st_distance().

Spatial Joins and Operations is a free R Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Spatial Joins with st_join

st_join(x, y) performs a spatial left join: for each feature in x, it finds features in y that satisfy a spatial predicate (default: st_intersects) and appends their attributes. Multiple matches produce multiple rows.

library(sf)

nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)

# Create random points within NC bounding box
set.seed(42)
bbox <- st_bbox(nc)
pts <- data.frame(
  lon = runif(20, bbox['xmin'], bbox['xmax']),
  lat = runif(20, bbox['ymin'], bbox['ymax'])
)
pts_sf <- st_as_sf(pts, coords = c('lon', 'lat'), crs = 4326)

# Spatial join: assign county attributes to each point
pts_with_county <- st_join(pts_sf, nc['NAME'])

cat('Points with county:\n')
print(head(pts_with_county[, c('NAME', 'geometry')], 5))

st_within: Point-in-Polygon

st_within(x, y) returns a sparse matrix of logical values indicating whether each feature in x falls completely within a feature in y. It is stricter than st_intersects — boundary touches do not count.

library(sf)

nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)

# Random points
set.seed(7)
bbox <- st_bbox(nc)
pts_sf <- st_as_sf(
  data.frame(
    lon = runif(30, bbox['xmin'], bbox['xmax']),
    lat = runif(30, bbox['ymin'], bbox['ymax'])
  ),
  coords = c('lon', 'lat'), crs = 4326
)

# Which points are within NC at all?
within_nc <- st_within(pts_sf, st_union(nc), sparse = FALSE)[, 1]
cat('Points within NC:', sum(within_nc), '/ 30\n')

# Keep only points inside NC
pts_inside <- pts_sf[within_nc, ]
cat('Kept:', nrow(pts_inside), 'points\n')

st_intersects: Overlap Test

st_intersects(x, y) returns TRUE when features share any geometry — boundary or interior. It is the most permissive topological predicate. Pass sparse = FALSE to get a logical matrix rather than a list of index vectors.

library(sf)

# Create two overlapping polygons
poly1 <- st_polygon(list(matrix(c(0,0, 2,0, 2,2, 0,2, 0,0), ncol=2, byrow=TRUE)))
poly2 <- st_polygon(list(matrix(c(1,1, 3,1, 3,3, 1,3, 1,1), ncol=2, byrow=TRUE)))
poly3 <- st_polygon(list(matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol=2, byrow=TRUE)))

sfc <- st_sfc(poly1, poly2, poly3, crs = 32119)

# Intersects matrix
mat <- st_intersects(sfc, sparse = FALSE)
cat('Intersects matrix:\n')
print(mat)
cat('\npoly1 intersects poly2:', mat[1, 2], '\n')
cat('poly1 intersects poly3:', mat[1, 3], '\n')

st_buffer: Creating Buffers

st_buffer(sf_obj, dist) creates a buffer polygon around each feature at the specified distance. In a geographic CRS the distance is in degrees; in a projected CRS it is in metres — always project before buffering for accurate results.

library(sf)

# City points in WGS84
cities <- data.frame(
  city = c('Raleigh', 'Charlotte', 'Greensboro'),
  lon  = c(-78.639, -80.843, -79.792),
  lat  = c(35.779,  35.227,  36.073)
)
cities_sf <- st_as_sf(cities, coords = c('lon', 'lat'), crs = 4326)

# Project to metres for accurate buffering (NC State Plane)
cities_proj <- st_transform(cities_sf, 32119)

# 25 km buffer around each city
buffers <- st_buffer(cities_proj, dist = 25000)

cat('Buffer geometry type:', unique(as.character(st_geometry_type(buffers))), '\n')
cat('Buffer area (km2):', round(as.numeric(st_area(buffers[1, ])) / 1e6, 2), '\n')
cat('Expected (pi*25^2):', round(pi * 25^2, 2), 'km2\n')

st_area: Polygon Areas

st_area(sf_obj) computes the area of each polygon. In a geographic CRS it returns values in steradians (not useful); in a projected CRS with metre units it returns square metres. Results carry units from the units package.

library(sf)
library(units)

nc <- read_sf(system.file('shape/nc.shp', package = 'sf'))
nc_proj <- st_transform(nc, 32119)  # NC State Plane, metres

# Area in m2 with units
nc_proj$area_m2 <- st_area(nc_proj)

# Convert to km2
nc_proj$area_km2 <- set_units(nc_proj$area_m2, 'km^2')

# Summary statistics
cat('Smallest county:', nc_proj$NAME[which.min(nc_proj$area_km2)],
    round(min(as.numeric(nc_proj$area_km2)), 1), 'km2\n')
cat('Largest county: ', nc_proj$NAME[which.max(nc_proj$area_km2)],
    round(max(as.numeric(nc_proj$area_km2)), 1), 'km2\n')

st_distance: Pairwise Distances

st_distance(x, y) computes a matrix of distances between all features in x and all in y. On WGS84 it uses geodesic distances; on projected CRS it uses Euclidean distances. Results carry units metadata.

library(sf)

cities <- data.frame(
  city = c('Raleigh', 'Charlotte', 'Greensboro', 'Wilmington'),
  lon  = c(-78.639, -80.843, -79.792, -77.909),
  lat  = c(35.779,  35.227,  36.073,  34.226)
)
cities_sf <- st_as_sf(cities, coords = c('lon', 'lat'), crs = 4326)

# Geodesic distance matrix (metres)
dist_m <- st_distance(cities_sf)
dist_km <- round(dist_m / 1000)

rownames(dist_km) <- cities$city
colnames(dist_km) <- cities$city

cat('Distance matrix (km):\n')
print(dist_km)

# Nearest neighbour for Raleigh
raleigh_dist <- as.numeric(dist_km['Raleigh', -1])
cat('\nNearest to Raleigh:',
    cities$city[-1][which.min(raleigh_dist)],
    min(raleigh_dist), 'km\n')

st_union: Dissolving Geometries

st_union(sf_obj) merges all features into a single geometry, dissolving interior boundaries. It is useful for creating a single outline polygon from multiple county polygons, or union-ing a set of buffers.

library(sf)

nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 32119
)

# Dissolve all counties into the NC state outline
nc_state <- st_union(nc)

cat('Counties before union:', nrow(nc), '\n')
cat('Features after union:', length(nc_state), '(single geometry)\n')
cat('Geometry type:', as.character(st_geometry_type(nc_state)), '\n')

# Area check: sum of counties == state area
county_area_sum <- sum(as.numeric(st_area(nc)))
state_area     <- as.numeric(st_area(nc_state))
cat('Sum of county areas:', round(county_area_sum / 1e9, 2), 'km2\n')
cat('State area:         ', round(state_area     / 1e9, 2), 'km2\n')

st_intersection: Clipping

st_intersection(x, y) returns the geometric intersection of each pair of features — the area that both geometries share. It is used for clipping one layer to the extent of another.

library(sf)

nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)

# Clip NC counties to a bounding rectangle (eastern NC)
clip_box <- st_as_sfc(st_bbox(c(
  xmin = -78, xmax = -75,
  ymin = 33.5, ymax = 36.5
), crs = 4326))

eastern_nc <- st_intersection(nc, clip_box)
cat('Original features:', nrow(nc), '\n')
cat('Clipped features: ', nrow(eastern_nc), '\n')
cat('Geometry types:   ', paste(unique(as.character(st_geometry_type(eastern_nc))), collapse = ', '), '\n')

Spatial Aggregation with dplyr

Combine st_join() with dplyr::group_by() and summarise() to aggregate point data by polygon. The geometry column is automatically summarised (unioned by default) when grouping an sf object.

library(sf)
library(dplyr)

nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 4326
)

# Generate random sales events in NC
set.seed(99)
bbox <- st_bbox(nc)
pts <- st_as_sf(
  data.frame(
    lon   = runif(200, bbox['xmin'], bbox['xmax']),
    lat   = runif(200, bbox['ymin'], bbox['ymax']),
    sales = runif(200, 100, 1000)
  ),
  coords = c('lon', 'lat'), crs = 4326
)

# Join then aggregate
result <- st_join(pts, nc['NAME']) |>
  filter(!is.na(NAME)) |>
  st_drop_geometry() |>
  group_by(NAME) |>
  summarise(total_sales = sum(sales), n_events = n()) |>
  arrange(desc(total_sales))

cat('Top 5 counties by sales:\n')
print(head(result, 5))

st_nearest_feature

st_nearest_feature(x, y) returns the index of the nearest feature in y for each feature in x. Combined with st_distance(), this gives both the nearest neighbour and its distance — useful for assignment problems.

library(sf)

# Hospitals (facilities)
hospitals <- data.frame(
  name = c('Hospital A', 'Hospital B', 'Hospital C'),
  lon  = c(-79.5, -80.2, -78.8),
  lat  = c(35.8,  35.3,  36.1)
)
hosp_sf <- st_as_sf(hospitals, coords = c('lon', 'lat'), crs = 4326)

# Patient locations
patients <- data.frame(
  id  = 1:5,
  lon = c(-79.9, -80.5, -79.0, -78.5, -80.1),
  lat = c(35.7,  35.2,  35.9,  35.5,  36.0)
)
pt_sf <- st_as_sf(patients, coords = c('lon', 'lat'), crs = 4326)

# Find nearest hospital for each patient
nearest_idx <- st_nearest_feature(pt_sf, hosp_sf)
pt_sf$nearest_hospital <- hospitals$name[nearest_idx]

print(st_drop_geometry(pt_sf))

Practical Workflow: Buffer and Count

A common real-world pattern: buffer a set of features (e.g. schools), then count how many points of interest (e.g. bus stops) fall within each buffer using st_join() and dplyr::count().

library(sf)
library(dplyr)

# Schools as points
schools <- data.frame(
  id  = 1:3,
  lon = c(-79.8, -80.2, -79.4),
  lat = c(35.9,  35.5,  36.1)
)
schools_sf <- st_as_sf(schools, coords = c('lon', 'lat'), crs = 4326) |>
  st_transform(32119)  # project to metres

# Random bus stops
set.seed(5)
stops <- data.frame(
  stop_id = 1:50,
  lon = rnorm(50, -79.8, 0.3),
  lat = rnorm(50,  35.8, 0.2)
) |>
  st_as_sf(coords = c('lon', 'lat'), crs = 4326) |>
  st_transform(32119)

# 2 km buffer around each school
buffers <- st_buffer(schools_sf, dist = 2000)
buffers$school_id <- schools$id

# Count bus stops within each school buffer
joined <- st_join(stops, buffers['school_id'])
counts <- count(st_drop_geometry(joined), school_id)
cat('Bus stops within 2km:\n')
print(counts)

Quick Check

You want to find all polygon features from layer B that overlap with each polygon in layer A, and append B's attributes to A. Which function should you use?

Recap: Spatial Joins and Operations

Key takeaways:

  • st_join(x, y) — spatial left join using a predicate (default: st_intersects)
  • st_within() — TRUE when x is fully inside y (boundary excluded)
  • st_intersects() — TRUE when any part of x touches y (most permissive)
  • st_buffer(sf_obj, dist) — create buffers; use projected CRS for metre-accurate buffers
  • st_area() / st_distance() — compute areas and distances (project first for accuracy)
  • st_union() — dissolve all features; st_intersection() — clip one layer to another
  • st_nearest_feature(x, y) — nearest neighbour lookup
library(sf)
nc <- st_transform(
  read_sf(system.file('shape/nc.shp', package = 'sf')), 32119
)

# Quick operations summary
cat('Largest county:', nc$NAME[which.max(st_area(nc))], '\n')
nc_outline <- st_union(nc)
cat('State area km2:', round(as.numeric(st_area(nc_outline)) / 1e6, 0), '\n')

Frequently asked questions

Is the “Spatial Joins and Operations” lesson free?

Yes — the full text of “Spatial Joins and Operations” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Spatial Joins and Operations”?

Apply st_join(), st_intersection(), st_buffer(), and st_distance(). You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Spatial Joins and Operations” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Simple Features with the sf Package
  2. Coordinate Reference Systems and Projections
  3. Spatial Joins and Operations
  4. Interactive Maps with leaflet
← Back to R Academy