Skip to contents

group_units() groups the units of a layer into contiguous groups whose size stays at most max, near target when one is given, and lifts groups below min where a neighbor has room under the cap. It builds pre-census enumeration areas from blocks, primary sampling units from enumeration areas, or any level above from the level below. With method = "merge", it only merges the units below min with their neighbors, as when small enumeration areas are merged into PSUs.

Usage

group_units(
  x,
  size,
  min = NULL,
  max = NULL,
  target = NULL,
  max_area = NULL,
  within = NULL,
  id = NULL,
  shape_weight = NULL,
  visible_weight = NULL,
  cross_below = 0,
  fixed = NULL,
  method = c("tree", "greedy", "merge"),
  refine = TRUE,
  seed = NULL,
  n = NULL,
  n_by = NULL,
  groups = NULL,
  graph = NULL
)

Arguments

x

An sf object (or sfc) of polygons in a projected CRS, one row per unit, or its unit_graph(). A layer gets the graph unit_graph(x, within = within) unless graph is given. Barriers, visible lines and patches need a graph built with them.

size

The size of each unit, such as population, households or buildings, or area, cropland or growing stock, as a nonnegative numeric vector in the row order of the layer, or as a column name of x when x is a layer. Sizes add up over the units of a group.

min

The smallest size a group should have, or NULL (default) for none. A group below it merges with a neighbor only when the merged group stays within max and max_area, so min gives way to the caps. Required by method = "merge".

max

The largest size a group may have, or NULL.

target

The size groups should be near, or NULL (default) for groups as large as the caps allow. It must lie between min and max. Unlike the caps, it is a goal, not a constraint.

Each of min, max and target is a single number, or one value per unit that is the same for every unit of a part of within, or a column name of x when x is a layer. Since no group crosses parts, each group then has the bounds of its part, as when the EAs of each stratum have their own size. NA in min or target means none for that part.

max_area

The largest area a group may have, in the squared units of the CRS, or NULL. Methods "tree" and "greedy" require at least one of max and max_area.

within

The part of the layer each unit lies in, such as its admin unit or stratum, as a column name of x or a vector, or NULL (default) for one part. No group crosses from one part to another. For a layer only, since a graph carries the parts it was built with.

id

The id of each unit, as a column name of x or a vector with no duplicates, or NULL (default). With it, each group takes the id of its first unit in row order, the convention of svyplan::merge_psus(), so every group traces to one unit.

shape_weight

The weight of compactness against size, in the local search (refine) and in the ranking of merges by method = "greedy". 0 ignores shape and gives the most even sizes, with elongated groups. NULL (default) means 0.5, or 0.05 with groups. On random lattices, 0.5 halved the spread of sizes compared with no local search, and raised compactness.

visible_weight

The weight of boundaries field staff cannot see, when the graph was built with visible lines (see unit_graph()). 0 ignores them. Larger values draw group boundaries along roads, paths and streams rather than across open ground, at some cost in the evenness of sizes. Ignored for a graph without visible lines. NULL (default) means 1, or 0.1 with groups. On rural test wards in Zimbabwe, 1 gave nearly all the reduction of invisible boundary that 2 gave. With groups, each group has a size of its own to reach, and the lighter weights let the search reach it. On a trial of 837 census EAs in Malawi, they left 3 to 4% of the groups more than 25% off their size over three seeds, against 9 to 10% with 0.5 and 1, with the same share of boundary on visible lines.

cross_below

Where barriers enclose land holding less than this size, they give way (see Details). The default 0 opens them only around empty land, such as the strip between two carriageways. Set it to min to let barriers that box in too little to make a group, as tertiary roads do in a city grid, be crossed there and nowhere else. Like min, it is a single number, or one value per unit that is the same for every unit of a part of within, or a column name of x when x is a layer, so each part opens its barriers at its own size.

fixed

Locked groups, as a vector with one value per unit: a group label for units whose group must not change, NA for free units. Units sharing a label stay together and are never merged with anything else, so a frame can be updated where it is stale and left as it is elsewhere. A locked group is kept as given, so a barrier crossing between two of its units counts as an edge. NULL (default) locks nothing.

method

"tree" (default), "greedy" or "merge". See Details.

refine

Whether to run the local search after the method, TRUE (default) or FALSE. See Details. method = "merge" never runs it.

seed

For method = "tree", an integer seed for the random tie breaks and tree roots, so a run can be repeated. Each part of within draws from the seed again, under R's default generator, so a run on some of the parts, with each level of n_by whole, gives them the groups of the full run whatever RNGkind() the session uses. The caller's random number stream is left as it was. "greedy" is deterministic and does not use it.

n

The number of groups, as a whole number, one value per unit that is the same within each level of n_by, or a column name of x when x is a layer, or NULL (default) for no count. It sets the target, so it cannot be given with target, and it applies to methods "tree" and "greedy". See Details.

n_by

The level the counts of n are for, as a column name of x or a vector, coarser than within, so that each part lies in one level, or NULL (default) for the parts of within. A level holding several parts, such as a stratum of several wards, shares its count among them.

groups

The groups to form, as a data frame with one row per group, such as the EAs of a census table or the compartments of a forest management plan, or NULL (default). Its column part gives the part of within the group lies in, size the size it should have, and id, optional, its code. part can be left out when the layer has one part. It must hold numbers where the parts hold numbers, and text where they hold text, so that codes such as "00123" are matched as written. Each part gets one group per row, cut toward its size (see Details). It states the count and the size of each group, so it cannot be given with n, n_by, target, fixed or id, and it applies to method = "tree".

graph

The unit_graph() of the layer x, or NULL (default). With it, the columns of x can be named, and the graph gives the parts, so within is left out. The call then reads like that of group_metrics(), and gives the result of the graph passed as x. It must be built from x itself, in the same row order. Only its number of units is checked, so a graph of a reordered or edited layer gives wrong results without an error.

Value

A vector with one group per unit. Without id, an integer vector numbered 1, 2, ... in order of first appearance. With id, a vector like id holding the id of each group's first unit. With groups, the id of each unit's row, or its row number without an id. Groups are numbered across the whole layer, not within each part, so a group joins back to its part without it.

Details

Barriers are hard, except where they enclose too little. After barriers, the graph falls into connected components. A component holding less than cross_below, or nothing at all, opens a crossing to a neighboring component, across the lowest barrier rank (see barrier_rank in unit_graph()), then the longest shared boundary, then, for links across gaps, the shortest distance, and the two look further out together until they hold enough. The opened crossings become ordinary edges, so groups may span them within the caps. With the default cross_below = 0, only empty land opens, such as the strip between the two carriageways of a divided road or the island of a roundabout, and no one is counted across a barrier. With cross_below = min, barriers give way where they box in less than a group, which happens where they are dense, as in a city grid, and hold where they are far apart, as in the countryside. A locked group (see fixed) is a component of its own that never crosses, so the free units next to it are weighed without it.

Before either method runs, two kinds of units are joined. Units sharing a fixed label become one locked unit. The units of a patch (see unit_graph()), connected units with one label, become one unit when their total size and area fit under the caps, so a village or a stand is never split between groups. A patch above the caps is partitioned like any other area.

The bond between two units is their shared boundary length. With visible lines, the part on a visible line counts 1 / (1 + visible_weight) of its length, so units across a road are bound more loosely than units across open ground, and groups tend to be cut along roads.

method = "tree" builds a spanning tree of the graph that keeps the strongest bonds between units, then cuts it into the fewest subtrees whose size is at most max, by the linear algorithm of Kundu and Misra (1977), which is exact for one cap on a tree. Every group is connected and within the caps by construction. With both max and max_area, the same cut is applied to the larger of the two loads, which is no longer guaranteed to give the fewest groups. With a target, each tree is cut at the smallest cap that gives it about total / target groups, found by bisection, so groups start near the target.

method = "greedy" merges neighboring groups in rounds, smallest group first, taking the merge that best combines a small resulting size with a compact shape, until no merge stays under the caps. With visible lines, the score of a merge also adds visible_weight times the visible share of the shared boundary. With a target, a merge is taken only when it brings the two groups closer to the target. The method follows the merge of the WorldPop preEA tool (Qader et al. 2021).

method = "merge" starts from every unit alone and runs only the last step below, which merges each group below min with a neighbor. Units already at or above min stay groups of their own unless a small neighbor joins them, and the local search does not run. The caps are optional and, when given, no merge goes past them. A group still below min at the end, such as an urban EA surrounded by rural ones of another stratum, gives a warning that names it. It is the contiguous counterpart of svyplan::merge_psus(), which merges in row order.

The local search then moves single units across group boundaries while doing so lowers a cost summed over groups. The cost of a group is its squared relative gap to target, a penalty ten times as heavy for each relative unit below min, shape_weight times one minus its isoperimetric quotient, and visible_weight times the length of its boundary with other groups that lies on no visible line, against the perimeter of a disk of the same area. A move is taken only when the receiving group stays within the caps and the giving group stays connected, so the search keeps every guarantee of the method. Locked units and kept patches move as wholes or not at all.

With n, the count of each level of n_by is shared among its parts in proportion to their size, by largest remainder, with at least one group for each part of the graph that no edge joins, and the count of each part among those parts the same way. Each gets the target that its count gives, and the method runs as with a target. The count of each part is then made exact: a part with too many groups merges its smallest group with its smallest neighbor among those the caps allow, and a part with too few cuts its largest group in two along the edge of a spanning tree that leaves the two halves nearest in size. The local search runs again, and it keeps the counts. With method = "greedy", a level still off its count is cut again by the tree method, which then runs once over the graph, and takes those groups where they come closer to the count. A count the search cannot reach gives way, with a warning that names the levels, the counts reached and the levels whose units allow fewer groups than their count, a locked group or a settlement kept whole counting as one unit. The search is not exhaustive, so another grouping may still reach it. The count comes before min, which a group may miss so that its part holds n.

The count also comes before cross_below. A level whose units still lie in more pieces than its count, once cross_below has opened what it opens, opens more barrier crossings and links across gaps (see gap in unit_graph()), one at a time, the one joining the two pieces that together hold the least first, until the pieces are no more than the count. Islands then join each other before they join the mainland. Pieces with no crossing or link between them stay apart, and the warning says so.

Groups below min are then merged with the neighbor they have the strongest bond with, among neighbors that keep the merge within the caps. A group with no such neighbor stays below min, and check_groups() reports it as forced. A unit larger than max on its own stays a group of its own.

With groups, the sizes of each part are first scaled to the size of its units, since a census table and sizes from buildings rarely add up to the same total. The rows of a part go to the pieces of its graph, each small piece taking the row nearest to its size and the largest piece the rest. Each piece's spanning tree is then cut, one subtree at a time. Of the subtrees within the caps that hold some size and leave the rest of the tree within the caps for its other rows, the one whose size is nearest, relative to the row, to one of the rows left is cut off and takes that row, until the rest of the tree takes the last row. When a group of more than one unit still passes a cap, the tree is cut again with the first subtree of each earlier try left out, up to 10 tries, and the try nearest the caps is kept. A row left over when no subtree fits cuts in two the group of its part with the most size for its row, or, when no group of the part can be cut with size on both sides, the group with the most units, so that every row gets a group. A warning names the parts where a row got a group with no size. The local search then runs with each group's own size as its target, within min and max, which never merge or split groups. The caps come before the sizes of the rows, so a row asking for more than max allows gets a smaller group, and a group left above a cap gets a warning with its row. Units of a piece with no size, or of more pieces than rows, with no link to the rest, get NA and a warning. Units cut too finely fit the sizes better, but split_units() cuts along buildings, not along roads, so more of the boundary then crosses open ground.

References

Kundu, S., and Misra, J. (1977). A linear tree partitioning algorithm. SIAM Journal on Computing, 6(1), 151-154. doi:10.1137/0206012

Qader, S., Lefebvre, V., Tatem, A. J., et al. (2021). Semi-automatic mapping of pre-census enumeration areas and population sampling frames. Humanities and Social Sciences Communications, 8, 3. doi:10.1057/s41599-020-00670-0

See also

unit_graph() for the graph, check_groups() to test the result, group_metrics() to measure how much of each boundary can be seen, dissolve_units() to turn the groups into polygons, split_units() to cut units above the cap before partitioning.

Other grouping and cutting functions: dissolve_units(), group_graph(), order_units(), split_units(), unit_graph()

Examples

cells <- sf::st_make_grid(
  sf::st_bbox(c(xmin = 0, ymin = 0, xmax = 1000, ymax = 800)),
  cellsize = 100
)
cells <- sf::st_sf(geometry = cells, crs = 32630)
set.seed(1)
cells$pop <- rpois(nrow(cells), 60)

g <- unit_graph(cells)
cells$ea <- group_units(
  g,
  cells$pop,
  min = 200,
  max = 500,
  target = 350,
  seed = 1
)
tapply(cells$pop, cells$ea, sum)
#>   1   2   3   4   5   6   7   8   9  10  11  12  13  14 
#> 365 366 378 344 357 338 381 386 352 376 345 261 308 328 

check_groups(g, cells$ea, cells$pop, min = 200, max = 500)
#> [1] check  group  units  size   forced detail
#> <0 rows> (or 0-length row.names)

# Exactly 6 groups, and then 4 in each commune
length(unique(group_units(g, cells$pop, n = 6, seed = 1)))
#> [1] 6
xy <- sf::st_coordinates(sf::st_centroid(sf::st_geometry(cells)))
cells$commune <- ifelse(xy[, 1] < 500, "west", "east")
gc <- unit_graph(cells, within = "commune")
table(cells$commune, group_units(gc, cells$pop, n = 4, seed = 1))
#>       
#>         1  2  3  4  5  6  7  8
#>   east  0  0 10 13  0  8  0  9
#>   west 12 10  0  0 10  0  8  0

# Groups sized from a table, one row per group, such as census EAs
census <- data.frame(part = c("west", "west", "east", "east", "east"),
  id = c("W1", "W2", "E1", "E2", "E3"),
  size = c(900, 1500, 600, 800, 1000))
cells$census_ea <- group_units(gc, cells$pop, groups = census, seed = 1)
tapply(cells$pop, cells$census_ea, sum)
#>   E1   E2   E3   W1   W2 
#>  609  909  952  906 1509 

# Merge EAs below 50 households into PSUs, within each stratum
eas <- sf::st_sf(
  ea = sprintf("EA%02d", 1:8),
  stratum = rep(c("north", "south"), each = 4),
  households = c(120, 12, 8, 95, 110, 20, 80, 70),
  geometry = sf::st_set_crs(sf::st_make_grid(
    sf::st_bbox(c(xmin = 0, ymin = 0, xmax = 400, ymax = 200)),
    cellsize = 100
  ), 32630)[c(1, 2, 5, 6, 3, 4, 7, 8)]
)
eas$psu <- group_units(eas, "households", min = 50,
  within = "stratum", id = "ea", method = "merge")
dissolve_units(eas, "psu", size = "households")
#> Simple feature collection with 5 features and 5 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 0 ymin: 0 xmax: 400 ymax: 200
#> Projected CRS: WGS 84 / UTM zone 30N
#>    psu stratum units households  area                       geometry
#> 1 EA01   north     2        132 20000 MULTIPOLYGON (((0 0, 0 100,...
#> 2 EA03   north     2        103 20000 MULTIPOLYGON (((0 100, 0 20...
#> 3 EA05   south     1        110 10000 MULTIPOLYGON (((200 0, 300 ...
#> 4 EA06   south     2         90 20000 MULTIPOLYGON (((400 0, 300 ...
#> 5 EA07   south     1         80 10000 MULTIPOLYGON (((200 100, 30...