<- sf::read_sf("~/data/adminexpress/adminexpress_cog_simpl_000_2022.gpkg",
dep layer = "departement")
|>
dep ::group_by(insee_reg) |>
dplyr::group_walk(\(grp_data, grp_name) sf::write_sf(grp_data,
dplyr::glue("~/temp/reg_{grp_name}.shp"))) glue
This old post sees a little traffic from search engines but is a mess after many editions due to the packages evolutions.
So, how can we (chose your term) append, merge, union or combine many shapefiles or other spatial vector data in 2023 with R, preferably using tidyverse functions?
For good measure, we want to add the source file as an attribute.
First, make some data using the geopackage available here. We generate several shapefiles (one per région) in a temporary directory:
This is the way
Current and concise.
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::map(\(f) sf::read_sf(f) |>
purrr::mutate(source = f, .before = 1)) |>
dplyr::bind_rows() dplyr
Approved
Recommended, as seen in the purrr help on map_dfr()
(that I liked better, see below) but verbose because we have to specify that we want a sf-tibble which is lost in translation.
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::map(\(f) sf::read_sf(f) |>
purrr::mutate(source = f, .before = 1)) |>
dplyr::list_rbind() |>
purrr::as_tibble() |>
dplyr::st_sf() sf
Superseded
… Sadly. That’s short and understandable.
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::map_dfr(\(f) sf::read_sf(f) |>
purrr::mutate(source = f, .before = 1)) dplyr
Older
I liked it, too.
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::tibble(source = _) |>
dplyr::mutate(shp = purrr::map(source, sf::read_sf)) |>
dplyr::unnest(shp) |>
tidyr::st_sf() sf
Oldest
Only if all files share the same attributes structure.
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::map(\(f) sf::read_sf(f) |>
purrr::mutate(source = f, .before = 1)) |>
dplyrdo.call(what = rbind)
or
::dir_ls("~/temp", regexp = ".*\\.shp$") |>
fs::map(\(f) sf::read_sf(f) |>
purrr::mutate(source = f, .before = 1)) |>
dplyr::reduce(rbind) purrr