[R-sig-Geo] How does sf do rgeos::gUnaryUnion or maptools::unionSpatialPolygons?

Roger Bivand Roger.Bivand at nhh.no
Tue May 9 15:32:32 CEST 2017


While https://github.com/edzer/sfr/wiki/migrating is very helpful, 
rgeos::gUnaryUnion is not the typical use case of sf::st_union. The 
typical use case, from ASDAR 1st edition, chapter 5 and the maptools 
"combine_maptools" vignette (the shapefiles are shipped with maptools), is 
grouping features that should belong to the same statistical entity:

library(maptools)
vignette("combine_maptools")

###################################################
### chunk number 16:
###################################################

library(sf)
nc90 <- st_read(system.file("shapes/co37_d90.shp", package = "maptools"))
st_crs(nc90) <- "+proj=longlat +datum=NAD27"
table(table(paste(nc90$ST, nc90$CO, sep="")))

The point is that two counties are represented by multiple features of 
"POLYGON" objects, rather than single "MULTIPOLYGON" objects, in the input 
shapefile. I've tried doing:

ids <- factor(paste(nc90$ST, nc90$CO, sep=""))
nc90a <- st_cast(nc90, to="MULTIPOLYGON", ids=as.integer(ids))

but:

> dim(nc90a)
[1] 104   9

all turned into "MULTIPOLYGON", but not grouped, even though I think ids= 
are as they should be:

> table(table(as.integer(ids)))

  1  2  4
98  1  1

This may be to avoid dropping data.frame rows. It looks as though I can 
get there using:

nc90a <- st_cast(st_geometry(nc90), to="MULTIPOLYGON", ids=as.integer(ids))

> length(nc90a)
[1] 100

but all are "MULTIPOLYGON", not a mixture of "POLYGON" and "MULTIPOLYGON" 
features, and I've no idea which is which - that is how the order of nc90a 
relates to the counties of nc90. How do I associate the features in 
nc90a with their county ids? Where do i find the ids I gave to st_cast in 
nc90a?

What am I missing? I'm writing here rather than raising an issue on GH 
because others may want to know too, and Edzer needs others to reply for 
him if they know the answer.

Puzzled,

Roger

-- 
Roger Bivand
Department of Economics, Norwegian School of Economics,
Helleveien 30, N-5045 Bergen, Norway.
voice: +47 55 95 93 55; e-mail: Roger.Bivand at nhh.no
Editor-in-Chief of The R Journal, https://journal.r-project.org/index.html
http://orcid.org/0000-0003-2392-6140
https://scholar.google.no/citations?user=AWeghB0AAAAJ&hl=en



More information about the R-sig-Geo mailing list