Create square or hexagonal grid polygons over a boundary
Source:R/tessellation.R
create_grid_polygons.RdLays a regular grid of equal-area cells over boundary and clips it to that
boundary. Use it rather than create_voronoi_polygons() when you set the
cell size yourself instead of letting the observations set it: per-cell
rates comparable across the map, or a resolution that stays fixed as the
sample grows. Hexagons (type = "hex") avoid the axis-aligned artefacts of
squares and put all six neighbours of a cell at the same distance.
Usage
create_grid_polygons(
boundary,
target_cells = NULL,
type = c("square", "hex"),
cellsize = NULL,
n = NULL,
clip = TRUE,
crs = NULL,
quiet = FALSE,
max_cells = 1e+06
)Arguments
- boundary
Polygonal sf or sfc object, the study area the grid is laid over and clipped to. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says. A boundary without a CRS that
crsstamps with a geographic CRS is tested for its latitude in the same way.- target_cells
Optional approximate desired number of cells. Besides a number it accepts what
approx_n_cellsofbuild_tessellation()accepts and reads it the same way: the ranked levels ofdetermine_optimal_levels()(the first is used), aselect_resolution()result (its$best) or aresolution_profile(), with the warnings and errors described there. The cell size is derived from it assqrt(area / target_cells), whereareais that of the boundary's bounding box, so square grids get square cells; for hex grids the count is adjusted for hexagonal packing density and the size rounded so that a whole number of hexagon widths spans the longer side of the box. The size does not depend on which way the boundary lies; the count can, because hexagon rows are 0.87cellsizeapart while columns arecellsizeapart (about 10 percent on a moderately elongated box, up to 1.7 times on a strip narrower than one hexagon). The count is approximate: square cells over an elongated bounding box need more cells than rectangles would (a 1000 x 1 strip attarget_cells = 9gives cells of side 10.5 and about 95 of them), and clipping to an irregular boundary moves the count again. Passcellsizewhen the count matters more than the shape.- type
Grid type:
"square"(the default) or"hex".- cellsize
Optional numeric cell size (length 1 or 2), in the units of the working CRS. Takes precedence over
nandtarget_cells: if either is also supplied,cellsizeis used, the other is ignored and a warning is logged. Supply exactly one oftarget_cells,cellsizeandn. Fortype = "hex"a hexagon is defined by a single edge-to-edge distance, so onlycellsize[1]is used and a differingcellsize[2]is ignored with a logged warning. A side of the boundary's bounding box that exceeds a whole number of square cells, of this size or of the size derived fromtarget_cells, by no more than a margin of one part in 1e10 of the largest coordinate of the boundary, at most a millionth of the diagonal of its bounding box and at least four times the spacing of doubles at that coordinate, gets that number of cells, so a box of 9000 by 6000 at 1000 gets 9 by 6 cells in any unit or origin, where rounding could add a row or column. A boundary so far from the origin of its coordinates that doubles there are spaced more than a millionth of its extent apart (0.125 at 1e15, beside a boundary a few kilometres across) has its grid lines rounded to that spacing; the grid is laid, and a warning of class"spatialkit_xy_imprecise"gives the spacing and the extent.- n
Optional grid resolution (integer, length 1 or 2) giving the number of columns and rows to divide the boundary's bounding box into; the cell size is derived from it.
sf::st_make_grid()derives hexagon placement fromcellsizealone, so fortype = "hex"ndoes not set the number of cells, although it does change the grid, because thecellsizederived from it is what the hexagons are built with. Ignored (with a logged warning) whencellsizeis also supplied. Passing both would otherwise truncate the grid ton[1]xn[2]cells anchored at the bounding-box corner, covering only part of the boundary. Wins overtarget_cells, which is then ignored with a logged warning.- clip
Logical; clip the grid to the boundary. Default
TRUE. In a projected or CRS-less grid, a cell that meets the boundary only within a margin of the cell's edge (the margincellsizegives: one part in 1e10 of the largest coordinate of the boundary, within its bounds; a cell whose edge lies on the boundary's edge up to rounding) is dropped, rather than kept as a sliver. The call stops when the clip leaves no cell, as it does when the lattice has none: in degrees with s2 on, a boundary edge that spans more than 180 degrees of longitude is read as the shorter great-circle arc, the other way round the globe.- crs
Optional target CRS: anything
sf::st_crs()accepts, including an sf or sfc layer, whose CRS is used. WhenNULL(default) a lon/lat boundary is projected withensure_projected(), which changes the CRS of the returned grid; a message reports this unlessquiet = TRUE. When that CRS would distort cell areas across the boundary by more than 1 percent (Web Mercator over a near-global extent, a UTM zone stretched well past its width),ensure_projected(purpose = "area")is used instead, with a logged warning, so the cells stay equal-area; a local extent keeps its UTM zone. A geographiccrs(EPSG:4326, say) is the CRS the grid is returned in: a grid sized bytarget_cellsornis laid in that projected CRS and then transformed, with long edges densified. Acellsizeis in the units ofcrs, so with a geographiccrsit is in degrees and the grid is laid in degrees, as asked; such cells are not equal-area. Withsf::sf_use_s2()on (the default) such a grid is clipped with sf's spherical engine s2, and s2 measures and joins its cells after; s2 refuses a polygon that is not valid on the sphere. The rows ofboundaryand the cells are checked with s2 whateversf::sf_use_s2()says. Before the clip, a row ofboundarythat s2 refuses is repaired, with crossing edges split. A cell that lists a corner twice in a row, or two corners within 1e-12 degrees of each other, which s2 reads as one point, is returned with one of them, which moves no corner and changes the cell's area by rounding. A row ofboundary, or a cell, that s2 refuses even then (a cell of a grid laid past latitude 90, say) stops the call with an error of class"spatialkit_cells_degenerate"that names its rows and s2's reason, and says to pass a projectedcrsor to size the grid bytarget_cellsorn.- quiet
Logical; suppress this function's progress
message()s. It does not silence R warnings, nor the package's console log echo (seespatialkit_quietfor that). DefaultFALSE.- max_cells
Upper bound on the number of cells the grid may have, estimated from the boundary's bounding box before anything is built. Default
1e6. Acellsizein the wrong units (metres on a boundary in kilometres, say) asks for a grid that cannot be built, and this refuses it with a message before memory is exhausted. Set toInfto disable.
Value
An sf polygon layer with one column, poly_id, numbering the
cells in the order sf::st_make_grid() lays them (row by row from the
bottom left). The numbering differs from that of
create_grid_polygons_cached() and ensure_stable_poly_id(), which
sort cells by position; pass the result to ensure_stable_poly_id() for
IDs that do not depend on how the grid was built. Use one builder
throughout an analysis, since a summary keyed on the IDs of one drawn on
the cells of the other puts the values on the wrong cells.
Details
Size the grid with exactly one of target_cells (roughly how many cells
you want; the package derives the rest), cellsize (a fixed edge length
in CRS units) or n (a fixed number of columns and rows). When more than
one is given, cellsize wins over the other two and n wins over
target_cells; each argument ignored is named in a logged warning.
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
grid_sq <- create_grid_polygons(bnd, target_cells = 100, type = "square")
grid_hex <- create_grid_polygons(bnd, target_cells = 100, type = "hex")
nrow(grid_sq)
#> [1] 100
# The hex count runs above the target: clipping keeps every hexagon that
# overhangs the boundary, and that adds more, in proportion, at a small
# target_cells.
nrow(grid_hex)
#> [1] 114