Skip to content

Instantly share code, notes, and snippets.

@kguidonimartins
Created March 7, 2022 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kguidonimartins/e196176f4d854d1624bd6f6939a49bd1 to your computer and use it in GitHub Desktop.
Save kguidonimartins/e196176f4d854d1624bd6f6939a49bd1 to your computer and use it in GitHub Desktop.
fix_invalid_geometries <- function(data) {
is_valid <- st_is_valid(data)
invalid_geom <- data[!is_valid, ]
geom_valid <- data[is_valid, ]
sf_use_s2(TRUE)
geom_invalid_fixed <-
invalid_geom %>%
s2::as_s2_geography(check = F) %>%
s2::s2_union() %>%
s2::s2_rebuild(s2::s2_options(split_crossing_edges = TRUE)) %>%
st_as_sf() %>%
bind_cols(invalid_geom %>% st_drop_geometry())
geom_fixed <-
bind_rows(geom_valid, geom_invalid_fixed)
return(geom_fixed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment