I might not have the correct language to exactly explain this, but I just discovered a case where using sf::st_combine
before calling sf::st_union
made a big difference to me.
I was using dplyr::group_by
and dplyr::summarise
to group an sf
tibble by a certain variable and then union each group to a single sf object:
sf_tibble %>%
dplyr::group_by(area) %>%
dplyr::summarise()
However, what I ended up with was multipolygon geometries, which is fine, but it meant that when I plotted my shapes with text labels, I ended up with multiple text labels for each area. I only wanted a single text label.
Then I tried using st_combine
first, then st_union
, and this solved my issue. I now only get single text labels for each area. To be explicit:
sf_tibble %>%
dplyr::group_by(area) %>%
dplyr::summarise(across(geometry, ~ sf::st_combine(.)), .groups = "keep") %>%
dplyr::summarise(across(geometry, ~ sf::st_union(.)), .groups = "drop")
[It may be that a plain dplyr::summarise()
is fine for one of those lines, and I'm not sure how important the .groups
bits are.]
(Edit:
sf_tibble %>%
dplyr::group_by(area) %>%
dplyr::summarise(across(geometry, ~ sf::st_combine(.)), .groups = "keep") %>%
# dplyr::summarise(across(geometry, ~ sf::st_union(.)), .groups = "drop")
dplyr::summarise()
seems to have the same effect as the code in the previous block.)
I realised that I might need to do this when I read that st_union
can be used to join overlapping and adjacent features
My areas were not all comprised of overlapping and adjacent features - some of them were coastal areas with separate islands. So then I realised that I maybe needed to combine the areas first, before unioning.