get_patches {flexurba} | R Documentation |
Detect patches of cells
Description
The function detects patches of cells based on rook contiguity (horizontal and vertical neighbours) or queen contiguity (horizontal, vertical and diagonal neighbours).
Patches of cells are groups of cells that are surrounded by NA
of NaN
values. The function identifies patches by converting the SpatRaster into polygons with the functions geos::as_geos_geometry()
and geos::geos_unnest()
. During this conversion polygons are automatically created as cells with rook contiguity. Touching polygons are afterwards dissolved to create patches with queen contiguity.
The function is similar as terra::patches()
, but is faster for large SpatRasters (see details).
Usage
get_patches(x, directions, cells = "all")
Arguments
x |
SpatRaster |
directions |
integer. Which cells are considered adjacent: |
cells |
character / vector. Either |
Details
The function is similar as terra::patches()
, but is faster for large SpatRasters.
Rook contiguity
Size SpatRaster | terra::patches(directions=4) | flexurba::get_patches(directions=4) |
4000 x 4000 (106 642 not-NA cells) | 75.157 s | 5.351 s |
4000 x 4000 (423 888 not-NA cells) | 324.846 s | 8.336 s |
Queen contiguity
Size SpatRaster | terra::patches(directions=8) | flexurba::get_patches(directions=8) |
4000 x 4000 (106 642 not-NA cells) | 37.322 s | 7.737 s |
4000 x 4000 (423 888 not-NA cells) | 183.428 s | 24.094 s |
Value
SpatRaster with patches of cells. The value of the cells represent the id of the patches.
Examples
r <- terra::rast(nrows = 8, ncols = 8, vals = c(
2, 2, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, 1, 1, 1, 1,
NA, NA, NA, NA, NA, 1, 1, 1,
2, NA, NA, NA, NA, NA, NA, NA,
NA, 2, NA, NA, NA, NA, NA, NA
))
terra::plot(r)
patches_rook1 <- get_patches(r, directions = 4)
terra::plot(patches_rook1)
patches_rook2 <- get_patches(r, directions = 4, cells = 1)
terra::plot(patches_rook2)
patches_queen1 <- get_patches(r, directions = 8)
terra::plot(patches_queen1)
patches_queen2 <- get_patches(r, directions = 8, cells = 1)
terra::plot(patches_queen2)