Detects invalid geometries with sf::st_is_valid(), reports them, and repairs the layer with sf::st_make_valid().

fix_invalid_geometries(data)

Arguments

data

An sf::sf object.

Value

An sf::sf object with the same attributes and geometry column name as data, with invalid geometries repaired.

Details

Rows with invalid geometries are reported via message() before sf::st_make_valid() is applied to the whole layer. Warnings emitted by the repair itself are suppressed. Geometries that become empty after the repair are kept and flagged with a warning() naming the affected rows. When every geometry is already valid, data is returned unchanged and no repair is attempted.

Examples

# \donttest{
crs_pl <- sf::st_crs(3857)
bowtie <- matrix(
  c(0, 0, 1e5, 0, 0, 1e5, 1e5, 1e5, 0, 0),
  ncol = 2L,
  byrow = TRUE
)
x <- sf::st_sf(
  id = "bowtie",
  geometry = sf::st_sfc(sf::st_polygon(list(bowtie)), crs = crs_pl)
)
fix_invalid_geometries(x)
#> [INFO] `{misc}`: 1 invalid geometry at row 1. Applying sf::st_make_valid()...
#> Simple feature collection with 1 feature and 1 field
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 0 ymin: 0 xmax: 1e+05 ymax: 1e+05
#> Projected CRS: WGS 84 / Pseudo-Mercator
#>       id                       geometry
#> 1 bowtie MULTIPOLYGON (((50000 50000...
# }