[R-sig-Geo] gUnaryUnion Not Dissolving Correctly

Matt Strimas-Mackey strimas at zoology.ubc.ca
Tue Nov 3 21:29:03 CET 2015


I'm working with a regular hexagonal grid stored as SPDF. At some
point I subset this SPDF, then want to combine all adjacent hexagons
together so that each contiguous set of hexagons is a single polygon.
I'm doing this last step using gUnaryUnion (or gUnionCascaded, not
clear what the different is actually). The problem is that in some
cases boundaries between clearly adjacent polygons are not dissolved.

Example:

## Create three adjacent hexagons
library(sp)
library(rgeos)
p1 <- Polygon(cbind(
      c(1276503.26781119, 1281876.11747031, 1287248.96712942,
        1287248.96712942, 1281876.11747031, 1276503.26781119, 1276503.26781119),
      c(204391.40834643, 207493.42454344, 204391.40834643, 198187.37595242,
        195085.35975541, 198187.37595242, 204391.40834643)))
p2 <- Polygon(cbind(
      c(1287248.96712943, 1292621.81678854, 1297994.66644766,
        1297994.66644766, 1292621.81678854, 1287248.96712943, 1287248.96712943),
      c(204391.40834643, 207493.42454344, 204391.40834643, 198187.37595242,
        195085.35975541, 198187.37595242, 204391.40834643)))
p3 <- Polygon(cbind(
      c(1281876.11747031, 1287248.96712943, 1292621.81678854,
        1292621.81678854, 1287248.96712943, 1281876.11747031, 1281876.11747031),
      c(213697.45693745, 216799.47313446, 213697.45693745, 207493.42454344,
        204391.40834643, 207493.42454344, 213697.45693745)))
spoly <- SpatialPolygons(list(Polygons(list(p1, p2, p3), 's1')))
plot(gUnaryUnion(spoly))

Note that p2 and p3 are dissolved together, but p1 is separate. The
shared edge of p1 and p2 is:
p1:
[2,] 1281876 207493.4
[3,] 1287249 204391.4
p2:
[5,] 1287249 204391.4
[6,] 1281876 207493.4

So, exactly the same apart from the order. I originally thought this
difference in order might be the problem, but this doesn't seem to be
an issue with in this example, where order is also flipped:
sss <- rasterToPolygons(raster(nrow=2, ncol=2, xmn=0, xmx=2, ymn=0,
ymx=2, vals=1:4))
lapply(sss at polygons, function(x) slot(x, 'Polygons')[[1]]@coords)
plot(sss)
plot(gUnaryUnion(sss))

Session Info:
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.5 (Yosemite)

Message when rgeos is loaded:

rgeos version: 0.3-14, (SVN revision 511)
GEOS runtime version: 3.5.0-CAPI-1.9.0 r0
Linking to sp version: 1.2-0
Polygon checking: TRUE

Any help on how to get these polygons to dissolve is appreciated.

M



More information about the R-sig-Geo mailing list