dwiz
dwiz

Reputation: 530

How to merge multiple sf polygons?

I am having trouble finding the best way to merge multiple sf polygons into one new sf polygon. I have been using st_union however that seems to only merge two sf objects pairwise.

The %>% notation works to pipe a bunch of st_union functions, but there must be a different way?

all <- st_union(rd) %>% st_union(cb) %>%  st_union(pl) %>% st_union(sl) %>%  
       st_union(wp) %>%  st_union(wf) %>%  st_union(bd) 

Also I find performance is really slow...

Upvotes: 4

Views: 16416

Answers (3)

Peter Scott
Peter Scott

Reputation: 21

If the polygons are in a list, try

st_combine(do.call("c", pol))

Upvotes: 2

dwiz
dwiz

Reputation: 530

This solution works for me:

single_sf <- dplyr::bind_rows(list(rd,cb,pl,sl,wp,wf,bd))
dissolve_sf <- st_union(single_sf)

Credit goes to this post: Convert a list of sf objects into one sf

Upvotes: 13

Joel Kandiah
Joel Kandiah

Reputation: 1525

There is a list/array object for sf objects called sfc we can construct this list using st_sfc(rd, cb, pl) and we can then combine these objects using sf_combine.

If I have understood correctly this can be seen in more detail:

https://r-spatial.github.io/sf/reference/sfc.html

and

https://r-spatial.github.io/sf/reference/geos_combine.html

All together I would expect the code to look like the following:

sfg_list <- st_sfc(rd, sb, pl, sl, wp, wf, bd)

st_combine(sfg_list)

Upvotes: 2

Related Questions