Skip to content
Prev 29211 / 29559 Next

Combine two polygons

Hi Milu,

If you want to combine just a few of the thousands of features in
world then you will have to manage them individually.  Essentially
extract the subset to be combined, do the combination steps, and then
add them back to the world.  I am very not familiar with GADM and I
only have version 4.1, but all of the attributes appear to be
character type, which raises the question about what you want
aggregate() to do - it can't take the mean of a character attribute.
In the example below I show how you might take just the first value of
each attribute.  While this combining is possible, it doesn't mean
that you will have "correct" attributes with your new single feature.
I guess you'll have to figure out what you really want to do with
that.

### start here
library(sf)
library(dplyr)
# a function called by aggregate() for each attribute
first_item = function(x){
  x[[1]]
}
# read in the database downlaoded from https://gadm.org/data.html
world = read_sf("~/Downloads/gadm_410.gpkg")
# find the Cypriot features (we'll use this twice)
ix = grepl("Cyp", world$NAME_0, fixed = TRUE)
# pull them out of world
Cyp_features = dplyr::filter(world, ix)
# aggregate - which works for the geometry but is wrong in terms of
handling the attributes
Cyp_union = aggregate(Cyp_features,
                      sf::st_union(Cyp_features),
                      first_item)
# bind the world (less Cypriot features) with the combined Cypriot aggregation
new_world = dplyr::bind_rows(dplyr::filter(world, !ix), Cyp_union)
### end here


Does that help?

Ben
On Fri, Apr 28, 2023 at 8:28?AM Roger Bivand <Roger.Bivand at nhh.no> wrote:
Message-ID: <CALrbzg2bnAw0ZwtRFoOkEQRK1qZQJaOo+Ek_iq3hezWK5X=6ZA@mail.gmail.com>
In-Reply-To: <SV0P279MB04754C382541D3016AB4E650EE6B9@SV0P279MB0475.NORP279.PROD.OUTLOOK.COM>