Skip to content

Instantly share code, notes, and snippets.

@kadyb
Created February 18, 2023 11:24
Show Gist options
  • Save kadyb/8a32c432a7b497b697379b483a8216d1 to your computer and use it in GitHub Desktop.
Save kadyb/8a32c432a7b497b697379b483a8216d1 to your computer and use it in GitHub Desktop.
Fast rows combine in {sf}
## This function is faster alternative to `rbind()` in the {sf} package.
## Basically, it uses `collapse::unlist2d()` to combine rows.
## See also: https://github.com/r-spatial/sf/issues/798
fastrbindsf = function(x, check = FALSE) {
if (length(x) == 0) stop("Empty list")
if (isTRUE(check)) {
ref_crs = sf::st_crs(x[[1]])
ref_colnames = colnames(x[[1]])
for (i in seq_len(length(x))) {
if (isFALSE(sf::st_crs(x[[i]]) == ref_crs)) stop("Diffrent CRS")
if (isFALSE(all(colnames(x[[i]]) == ref_colnames))) stop("Diffrent columns")
}
}
geom_name = attr(x[[1]], "sf_column")
x = collapse::unlist2d(x, idcols = FALSE, recursive = FALSE)
x[[geom_name]] = sf::st_sfc(x[[geom_name]], recompute_bbox = TRUE)
x = sf::st_as_sf(x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment