[R-sig-Geo] keep just one polygon for each element

Robert J. Hijmans r.hijmans at gmail.com
Tue Mar 3 23:10:19 CET 2015


Leo, here is an approach that might work for you:

library(raster)
library(rgdal)
library(rgeos)
library(plyr)

# create some example data.
p <- shapefile(system.file("external/lux.shp", package="raster"))
p <- p[, 'NAME_1']
p <- aggregate(p, 'NAME_1', dissolve=FALSE)

# now we have 3 regions, each consisting of multiple polygons.
# let's get the largest polygon in each region

p$id1 <- 1:length(p)
pp <- disaggregate(p)
pp$id2 <- 1:length(pp)
pp$area <- gArea(pp, byid=TRUE)

d <- ddply(data.frame(pp), ~id1, function(x){x[which.max(x$area),]})
r <- pp[d$id2, ]


# show the results
plot(pp, col=rainbow(4)[pp$id1])
plot(r, border='blue', add=TRUE, lwd=3)

On Tue, Mar 3, 2015 at 6:15 AM, Leonardo Monasterio
<leonardo.monasterio at gmail.com> wrote:
> Dear all,
>
> I have a quite detailed SpatialPolygon of thousands of municipalities. Most
> elements are formed by just one polygon, but some - thanks to islands or
> rivers- are formed by multiple ones. These tiny polygons are useless to me.
>
> Question: Is there a way create a SpatialPolygon formed by the largest
> polygon of each element?
>
> I've checked this:
> http://www.r-bloggers.com/simplifying-polygon-shapefiles-in-r/
>
> But it is not exactly what I am looking for.
>
> Yours thankfully,
>
> Leo.
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list