Skip to contents

decoupage keeps few functions and leaves to a few lines of code what a few lines can do. This vignette gathers those lines. Most recipes run on a small grid of cells, in two communes and crossed by a road, so they can be pasted and adapted.

library(decoupage)
library(sf)

cells <- st_make_grid(st_bbox(c(xmin = 0, ymin = 0, xmax = 800,
  ymax = 600)), cellsize = 100)
cells <- st_sf(geometry = st_set_crs(cells, 32630))
cells$commune <- ifelse(st_coordinates(st_centroid(cells))[, 1] < 400,
  "A", "B")
set.seed(1)
cells$pop <- rpois(nrow(cells), 60)
road <- st_sf(name = "Route de Yako", geometry = st_sfc(
  st_linestring(rbind(c(0, 300), c(800, 300))), crs = 32630))
g <- unit_graph(cells, within = "commune", visible = road)
cells$ea <- group_units(g, cells$pop, max = 400, target = 300, seed = 1)
## Different colors for neighboring polygons
paint <- function(x, pal = hcl.colors(6, "Set 2")) {
  nb <- st_intersects(x)
  col <- integer(nrow(x))
  for (i in order(-lengths(nb))) {
    col[i] <- setdiff(seq_along(pal), col[setdiff(nb[[i]], i)])[1]
  }
  pal[col]
}

Each cell holds about 60 persons, and group_units() gathers the cells into EAs of at most 400 persons that stop at the commune line. The maps below draw the units in white and the groups in color.

eas <- dissolve_units(cells, "ea", size = "pop")
communes <- dissolve_units(cells, "commune", size = "pop")
par(mar = rep(0, 4))
plot(st_geometry(eas), col = paint(eas), border = NA)
plot(st_geometry(cells), border = "white", add = TRUE)
plot(st_geometry(communes), lwd = 2, add = TRUE)
plot(st_geometry(road), lwd = 2, lty = 2, add = TRUE)
text(st_coordinates(st_point_on_surface(st_geometry(eas))),
  labels = eas$pop, cex = 0.8)
The cells and their EAs, with the population of each EA, the commune line in black and the road dashed.

The cells and their EAs, with the population of each EA, the commune line in black and the road dashed.

Checking inputs

Every function reads lengths and areas, so every vector layer should be in a projected CRS in meters, such as the local UTM zone. A layer holds one row per unit with a persistent id, such as an EA code, which carries the lineage from a segment back to its PSU. check_units() lists the defects of a polygon layer without changing anything. Given a boundary layer, it also lists units that cross its lines and land no unit covers, and given sizes, units out of bounds.

check_units(cells, size = "pop", min = 50, max = 80)
#>       check row other area           detail
#> 1 below_min   5    NA   NA size 48 below 50
#> 2 below_min  21    NA   NA size 44 below 50
#> 3 below_min  30    NA   NA size 49 below 50
#> 4 below_min  40    NA   NA size 47 below 50

What to do with a finding is the user’s decision. Overlaps between areas digitized one by one are common, and unit_graph() links overlapping units by default. A gap may be a lake, or land the layer forgot. Lines need less care, since blocks tolerate dead ends and duplicated segments.

Inputs from Overture Maps

Overture publishes its themes as GeoParquet files on public cloud storage, and DuckDB reads only the rows whose bounding box meets the area, with no account. Record the release, since layers change between releases.

library(DBI)
con <- dbConnect(duckdb::duckdb())
for (sql in c("INSTALL spatial", "LOAD spatial", "INSTALL httpfs",
  "LOAD httpfs", "SET s3_region = 'us-west-2'")) {
  dbExecute(con, sql)
}
release <- "2026-09-23.1"
bb <- c(xmin = -2.28, ymin = 12.96, xmax = -2.23, ymax = 13.02)
where <- sprintf(paste("bbox.xmin <= %f AND bbox.xmax >= %f AND",
  "bbox.ymin <= %f AND bbox.ymax >= %f"),
  bb[["xmax"]], bb[["xmin"]], bb[["ymax"]], bb[["ymin"]])
url <- function(theme, type) {
  sprintf("s3://overturemaps-us-west-2/release/%s/theme=%s/type=%s/*",
    release, theme, type)
}
roads <- dbGetQuery(con, sprintf(
  "SELECT class, ST_AsWKB(geometry) AS wkb FROM read_parquet('%s',
   hive_partitioning = 1) WHERE subtype = 'road' AND %s",
  url("transportation", "segment"), where))
roads <- st_transform(st_sf(class = roads$class, geometry = st_as_sfc(
  structure(roads$wkb, class = "WKB"), crs = 4326)), 32630)
## A point on each building with its area is enough, and much lighter
buildings <- dbGetQuery(con, sprintf(
  "SELECT ST_X(ST_PointOnSurface(geometry)) AS lon,
          ST_Y(ST_PointOnSurface(geometry)) AS lat,
          ST_Area_Spheroid(geometry) AS area_m2
   FROM read_parquet('%s', hive_partitioning = 1) WHERE %s",
  url("buildings", "building"), where))
buildings <- st_transform(st_as_sf(buildings, coords = c("lon", "lat"),
  crs = 4326), 32630)
dbDisconnect(con, shutdown = TRUE)

Overture roads come from OpenStreetMap under the Open Database License, and its buildings combine OpenStreetMap with machine footprints under their own licenses. Boundaries come best from COD-AB on the Humanitarian Data Exchange, agreed with governments, after checking their date against reforms. Population rasters come from WorldPop or GHS-POP.

Carrying a class raster to units

measure_units() returns sums. A class raster, such as the Degree of Urbanisation grid of the GHSL, is carried to units by the class covering most of each, with exactextractr::exact_extract() in the raster’s CRS. Adding the class to within, as paste(commune, class), then keeps groups from straddling a class edge.

smod <- terra::rast(xmin = 0, xmax = 800, ymin = 0, ymax = 600,
  resolution = 200, crs = "EPSG:32630", vals = rep(c(30, 30, 13, 11), 3))
eas$smod <- exactextractr::exact_extract(smod,
  st_transform(eas, terra::crs(smod)), "majority", progress = FALSE)
table(eas$smod)
#> 
#> 11 13 30 
#>  2  3  5

classes <- c("11" = "#d9f0d3", "13" = "#fee391", "30" = "#fdae61")
cls <- st_as_sf(terra::as.polygons(smod))
par(mfrow = c(1, 2), mar = c(0, 0, 1.5, 0))
plot(st_geometry(cls), col = classes[as.character(cls[[1]])],
  border = NA, main = "Raster")
plot(st_geometry(eas), add = TRUE)
plot(st_geometry(eas), col = classes[as.character(eas$smod)],
  main = "Class of each EA")
The class raster, urban in orange, villages in yellow and rural land in green, and the class of each EA.

The class raster, urban in orange, villages in yellow and rural land in green, and the class of each EA.

An agricultural area frame

An area frame cuts land into PSUs within land-use strata, sized by area, and divides a selected PSU into segments whose lines field staff can find. Here two strata and two districts cross on a territory of 6 by 4 km, and roads and a stream cut it into blocks. PSUs nest in both layers, so build_blocks() cuts their intersection, and the part of a block is its district and stratum pasted together. Blocks carry their area in the squared units of the CRS, here m2, which max_area takes too, and the size is that area in km2.

square <- function(x0, y0, x1, y1) {
  st_polygon(list(rbind(c(x0, y0), c(x1, y0), c(x1, y1), c(x0, y1),
    c(x0, y0))))
}
strata <- st_sf(stratum = c("cropland", "rangeland"), geometry = st_sfc(
  square(0, 0, 3500, 4000), square(3500, 0, 6000, 4000), crs = 32630))
districts <- st_sf(district = c("north", "south"), geometry = st_sfc(
  square(0, 2000, 6000, 4000), square(0, 0, 6000, 2000), crs = 32630))
st_agr(strata) <- "constant"
st_agr(districts) <- "constant"
land <- st_intersection(strata, districts)
lines <- st_sfc(c(
  lapply(seq(500, 3500, by = 750), function(y) {
    st_linestring(rbind(c(-10, y), c(6010, y + 200)))
  }),
  lapply(seq(700, 5500, by = 900), function(x) {
    st_linestring(rbind(c(x, -10), c(x - 150, 4010)))
  })
), crs = 32630)
blocks <- build_blocks(land, lines)
blocks$km2 <- blocks$area / 1e6
blocks$part <- paste(blocks$district, blocks$stratum)
## PSUs of about 1 km2 in cropland and 2 km2 in rangeland
target <- ifelse(blocks$stratum == "cropland", 1, 2)
g_af <- unit_graph(blocks, within = "part", visible = lines)
blocks$psu <- group_units(g_af, blocks$km2, min = 0.5 * target,
  max = 1.6 * target, target = target, seed = 1)
psus <- dissolve_units(blocks, "psu", size = "km2")
aggregate(km2 ~ district + stratum, st_drop_geometry(psus), range)
#>   district   stratum     km2.1     km2.2
#> 1    north  cropland 0.7110061 1.2993517
#> 2    south  cropland 0.6148856 1.3836261
#> 3    north rangeland 2.3811470 2.6188530
#> 4    south rangeland 1.5246269 1.8000000

par(mar = rep(0, 4))
plot(st_geometry(psus), col = paint(psus), border = NA)
plot(st_geometry(blocks), border = "white", add = TRUE)
plot(st_geometry(land), lwd = 2, add = TRUE)
plot(st_geometry(psus[1, ]), border = "red", lwd = 2, add = TRUE)
text(st_coordinates(st_point_on_surface(st_geometry(psus))),
  labels = round(psus$km2, 1), cex = 0.7)
Blocks in white, PSUs in color with their area in km2, the strata and districts in black, and the PSU cut below in red.

Blocks in white, PSUs in color with their area in km2, the strata and districts in black, and the PSU cut below in red.

A selected PSU becomes segments of whole blocks with n, so every segment line is a road or the stream.

inner <- blocks[blocks$psu == psus$psu[1], ]
inner$segment <- group_units(inner, "km2", n = 2, seed = 1)
tapply(inner$km2, inner$segment, sum)
#>         1         2 
#> 0.2511109 0.6741643

Where a PSU holds fewer blocks than segments, split_units() with lines cuts it along minor lines left out of the blocks, such as tracks and field edges, and cuts straight only inside a face too large for a segment. visible gives the share of each segment’s cut boundary that runs along those lines.

edges <- st_sfc(lapply(seq(0, 6000, by = 250), function(x) {
  st_linestring(rbind(c(x, -10), c(x + 40, 4010)))
}), crs = 32630)
segments <- split_units(psus[1, ], "km2", max = 0.4, target = 0.3,
  lines = edges)
st_drop_geometry(segments)[c("psu", "km2", "visible")]
#>   psu       km2 visible
#> 1   1 0.1947696       1
#> 2   1 0.2137748       1
#> 3   1 0.2116980       1
#> 4   1 0.3050327       1

two <- dissolve_units(inner, "segment")
par(mfrow = c(1, 2), mar = c(0, 0, 1.5, 0))
plot(st_geometry(two), col = paint(two), border = NA,
  main = "Whole blocks")
plot(st_geometry(inner), border = "white", add = TRUE)
plot(st_geometry(segments), col = paint(segments), border = "white",
  main = "Field edges")
plot(st_intersection(edges, st_geometry(psus[1, ])), lty = 3,
  add = TRUE)
The PSU cut into two segments of whole blocks (left) and along field edges, dotted (right).

The PSU cut into two segments of whole blocks (left) and along field edges, dotted (right).

A forest inventory

A stand-based inventory groups stands into inventory blocks within management units, sized by area or growing stock, with stands kept whole where they fit. Forest roads cut stands into pieces, so each piece carries its stand, and patch keeps the pieces of a stand together. A river no crew crosses is a barrier.

set.seed(4)
units <- st_sf(mu = c("A", "B"), geometry = st_sfc(
  square(0, 0, 3000, 3000), square(3000, 0, 5000, 3000), crs = 32630))
seeds <- st_sample(st_union(units), 60)
cells_v <- st_collection_extract(st_voronoi(st_union(seeds),
  envelope = st_as_sfc(st_bbox(units))), "POLYGON")
st_agr(units) <- "constant"
stands <- st_intersection(st_sf(geometry = cells_v), units)
stands$stand <- sprintf("S%02d", seq_len(nrow(stands)))
forest_roads <- st_sfc(st_linestring(rbind(c(-10, 1200), c(5010, 1500))),
  st_linestring(rbind(c(2000, -10), c(2300, 3010))), crs = 32630)
river <- st_sfc(st_linestring(rbind(c(4200, -10), c(4400, 3010))),
  crs = 32630)

pieces <- build_blocks(stands, c(forest_roads, river))
pieces$ha <- pieces$area / 1e4
g_fi <- unit_graph(pieces, within = "mu", patch = "stand",
  barrier = river, visible = forest_roads)
pieces$block <- group_units(g_fi, pieces$ha, min = 50, max = 120,
  target = 90, seed = 1)
range(tapply(pieces$ha, pieces$block, sum))
#> [1]  61.65772 111.84665
nrow(check_groups(g_fi, pieces$block, pieces$ha, min = 50, max = 120))
#> [1] 0

inventory <- dissolve_units(pieces, "block")
par(mar = rep(0, 4))
plot(st_geometry(inventory), col = paint(inventory), border = NA)
plot(st_geometry(stands), border = "white", add = TRUE)
plot(st_geometry(inventory), border = "grey20", add = TRUE)
plot(forest_roads, col = "grey40", lwd = 2, add = TRUE)
plot(river, col = "#3182bd", lwd = 3, add = TRUE)
plot(st_geometry(units), lwd = 2, add = TRUE)
Inventory blocks in color with a dark outline, stands in white, forest roads in grey, the river in blue and the line between management units in black.

Inventory blocks in color with a dark outline, stands in white, forest roads in grey, the river in blue and the line between management units in black.

A stock raster is measured the same way, with measure_units(pieces, raster = stock, inside = forest), so clearings outside the forest mask get none. When a management unit is redrawn, renest_units() carries the blocks to the new lines, and only the blocks the lines cross change.

Reconciling a frame edited by hand

Cartographers edit a frame before fieldwork. check_units() lists the defects of the edited frame, code_units() with previous keeps the codes of unchanged areas and gives the pieces of a split one child codes, and crosswalk_units() returns the correspondence.

eas$code <- code_units(eas, "commune", digits = 2)
## The first EA is split in two
halves <- st_intersection(st_sf(geometry = st_make_grid(
  st_geometry(eas)[1], n = c(2, 1))), st_geometry(eas)[1])
edited <- rbind(eas[-1, "commune"],
  st_sf(commune = eas$commune[1], geometry = st_geometry(halves)))
edited$pop <- measure_units(edited,
  points = st_centroid(st_geometry(cells)), weight = cells$pop)
edited$code <- code_units(edited, "commune", digits = 2, previous = eas)
cw <- crosswalk_units(eas, edited, "code", "code")
cw[cw$old != cw$new, ]
#>   old   new  area area_old area_new
#> 1 A01 A01-1 30000      0.5        1
#> 2 A01 A01-2 30000      0.5        1

kept <- intersect(eas$code, edited$code)
par(mfrow = c(1, 2), mar = c(0, 0, 1.5, 0))
frames <- list(Before = eas, Edited = edited)
for (k in names(frames)) {
  x <- frames[[k]]
  plot(st_geometry(x), border = "white", main = k,
    col = ifelse(x$code %in% kept, "grey85", "#fdae61"))
  text(st_coordinates(st_point_on_surface(st_geometry(x))),
    labels = x$code, cex = 0.7)
}
EA codes before and after the edit, with the EA split in two in orange.

EA codes before and after the edit, with the EA split in two in orange.

Comparing groupings and describing boundaries

group_metrics() on two groupings, side by side, compares the count of groups, the spread of their sizes, their shapes and the share of their boundaries field staff cannot see.

greedy <- group_units(g, cells$pop, max = 400, target = 300,
  method = "greedy")
summarise <- function(group) {
  m <- group_metrics(cells, group, size = cells$pop, graph = g)
  c(groups = nrow(m), cv = sd(m$size) / mean(m$size), ipq = mean(m$ipq),
    invisible = mean(m$invisible_share))
}
round(rbind(tree = summarise(cells$ea), greedy = summarise(greedy)), 3)
#>        groups    cv   ipq invisible
#> tree       10 0.218 0.716     0.400
#> greedy     11 0.264 0.690     0.432

par(mfrow = c(1, 2), mar = c(0, 0, 1.5, 0))
for (k in c("tree", "greedy")) {
  x <- dissolve_units(cells, if (k == "tree") cells$ea else greedy)
  plot(st_geometry(x), col = paint(x), border = NA, main = k)
  plot(st_geometry(cells), border = "white", add = TRUE)
  plot(st_geometry(road), lwd = 2, lty = 2, add = TRUE)
}
The EAs of the tree method (left) and of the greedy method (right), with the road dashed.

The EAs of the tree method (left) and of the greedy method (right), with the road dashed.

With the graph, group_metrics() also splits each perimeter into the part on a within line or the edge (outer), and the part shared with other groups along a visible line (visible) or across open ground (invisible). Areas with much invisible boundary need landmarks on their map sheet, and graph_lines() draws the edges for a GIS.

A frame from a settlement directory

A census often holds a directory of settlements, each with a point, its codes and its counts. assign_units() gives each block to a settlement of its admin unit, so the codes reach the land along block edges. Each settlement then gets the EAs it is coded for, with n and the settlements as parts.

directory <- st_sf(
  name = c("Bassi", "Daka", "Seno", "Kolo"),
  commune = c("A", "A", "B", "B"),
  households = c(140, 30, 90, 60),
  eas = c(3, 1, 2, 1),
  geometry = st_sfc(st_point(c(150, 150)), st_point(c(300, 500)),
    st_point(c(500, 200)), st_point(c(700, 450)), crs = 32630)
)
blocks <- assign_units(cells[, "commune"], directory, within = "commune")
## The households of a settlement spread over its blocks by area
blocks$households <- blocks$households * as.numeric(st_area(blocks)) /
  ave(as.numeric(st_area(blocks)), blocks$name, FUN = sum)
g_set <- unit_graph(blocks, within = "name")
blocks$ea <- group_units(g_set, blocks$households, n = blocks$eas,
  seed = 1)
tapply(blocks$ea, blocks$name, function(z) length(unique(z)))
#> Bassi  Daka  Kolo  Seno 
#>     3     1     1     2

settled <- dissolve_units(blocks, "name")
par(mar = rep(0, 4))
plot(st_geometry(settled), col = paint(settled), border = NA)
plot(st_geometry(dissolve_units(blocks, "ea")), lwd = 1.5, add = TRUE)
plot(st_geometry(directory), pch = 19, add = TRUE)
text(st_coordinates(directory), labels = directory$name, pos = 3,
  cex = 0.8)
The blocks of each settlement in color and its EAs in black, with the settlements as points.

The blocks of each settlement in color and its EAs in black, with the settlements as points.

A frame from a table of records

A census often publishes a table of its EAs, each with the code of its admin unit and its households, but no map. group_units() with groups cuts each admin unit into one group per row, toward its size, and gives each group the id of its row. check_units() with id and groups first lists where the table and the polygons disagree, such as a town coded under the commune around it.

census <- data.frame(
  part = rep(c("A", "B"), c(5, 4)),
  id = c("A01", "A02", "A03", "A04", "A05", "B01", "B02", "B03", "B04"),
  size = c(80, 95, 110, 70, 90, 140, 160, 75, 85)
)
check_units(communes, id = "commune", groups = census)
#> [1] check  row    other  area   detail
#> <0 rows> (or 0-length row.names)
g_rec <- unit_graph(cells, within = "commune", gap = Inf)
cells$census_ea <- group_units(g_rec, cells$pop, groups = census,
  seed = 1)
check_groups(g_rec, cells$census_ea, cells$pop, groups = census)
#> [1] check  group  units  size   forced detail
#> <0 rows> (or 0-length row.names)

rows <- dissolve_units(cells, "census_ea")
par(mar = rep(0, 4))
plot(st_geometry(rows), col = paint(rows), border = NA)
plot(st_geometry(cells), border = "white", add = TRUE)
plot(st_geometry(communes), lwd = 2, add = TRUE)
text(st_coordinates(st_point_on_surface(st_geometry(rows))),
  labels = rows$census_ea, cex = 0.8)
The EAs of the census table, each with the id of its row.

The EAs of the census table, each with the id of its row.

The cells are sized by population, and group_units() scales these sizes to the households of the table, part by part. gap = Inf links land cut off from the rest of its part, such as an island, so every part can reach the rows of its table.

Large areas, one admin unit at a time

A country can be built one admin unit at a time, in separate R processes. Two rules make the results those of a single run. A task holds whole parts of within, and whole levels of n_by when n is given, and group_units() gets a seed, from which each part draws again. A trial on one district is then a preview of the full run. The function of a task names the package of each call and returns its warnings, since a worker reports only what it returns.

tasks <- lapply(split(seq_len(nrow(cells)), cells$commune), function(i) {
  part <- cells[i, ]
  list(cells = part, road = road[lengths(st_intersects(road,
    st_union(part))) > 0, ])
})
one_commune <- function(task) {
  warned <- character(0)
  value <- withCallingHandlers({
    g <- decoupage::unit_graph(task$cells, within = "commune",
      visible = task$road)
    task$cells$ea <- decoupage::group_units(g, task$cells$pop,
      max = 400, target = 300, seed = 1)
    task$cells
  }, warning = function(w) {
    warned <<- c(warned, conditionMessage(w))
    invokeRestart("muffleWarning")
  })
  list(value = value, warnings = warned)
}
out <- lapply(tasks, one_commune)
## The same EAs as the single run above
vapply(names(out), function(k) {
  a <- cells$ea[cells$commune == k]
  b <- out[[k]]$value$ea
  identical(match(a, unique(a)), match(b, unique(b)))
}, logical(1))
#>    A    B 
#> TRUE TRUE

In parallel, the tasks go to mirai daemons, largest first so it does not start last. Their results are put back in the order of the tasks, and the pieces are bound with ids made unique.

by_size <- order(-vapply(tasks, function(t) nrow(t$cells), integer(1)))
mirai::daemons(4)
out <- mirai::mirai_map(tasks[by_size], one_commune)[.stop]
mirai::daemons(0)
out <- out[order(by_size)]
eas <- do.call(rbind, lapply(out, `[[`, "value"))
eas$ea <- paste(eas$commune, eas$ea)

Recording a run

A frame is used for years, so its sources and settings should travel with it. A one-row table next to the layer in a GeoPackage survives a write and a read, and the hash of each input file identifies it.

input <- system.file("extdata", "yako.gpkg", package = "decoupage")
gpkg <- tempfile(fileext = ".gpkg")
write_sf(cells, gpkg, layer = "eas")
run <- data.frame(
  created = format(Sys.time(), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"),
  decoupage = as.character(packageVersion("decoupage")),
  GEOS = sf_extSoftVersion()[["GEOS"]],
  roads = "Overture 2026-09-23.1",
  input_md5 = unname(tools::md5sum(input)),
  max = 400, target = 300, seed = 1
)
write_sf(run, gpkg, layer = "eas_run")
st_layers(gpkg)$name
#> [1] "eas"     "eas_run"

Where decoupage stops

decoupage returns areas, ids, sizes, an order and flags. It draws no sample and attaches no probabilities or weights, which belong to samplyr, sondage and svyplan. It groups by size and shape, not by the similarity of attributes, which regionalization methods such as spdep::skater() or rgeoda serve. It cuts polygons, not networks or point grids, so routes and the plot grids of national forest inventories are outside it. Areas merged up to a minimum count can serve as statistical geography, but a minimum size alone is not a confidentiality guarantee.