Dissolve all polygons but one from a shape file


I want to dissolve all polygons but one from a shape file. Is there a way to do this?

Here is a reproducible example:

library(rgeos)
library(UScensus2000tract)

# load data
  data("oregon.tract")

# plot map
  plot(oregon.tract)

enter image description here

# Dissolve all polygons
  d <- gUnaryUnion(oregon.tract, id = oregon.tract@data$state)
  plot(d)

enter image description here

In this example, is it possible to dissolve the polygons by keep the tract number 9501 ?


Answers:


I assume this is what you are looking for. This is slightly different if you want to merge contiguous members of the tract together, but all you would have to do is remove the first element (the entire state) from the polygon, and then run gUnaryUnion on the remainder, and then re-add the contiguous tract members to a copy of the gUnaryUnion-ized state.

oregon = oregon.tract
names(attributes(oregon.tract))
#[1] "bbox"        "proj4string" "polygons"    "plotOrder"   "data"       
#[6] "class"
selected_tract_indices = which(oregon.tract@data$tract == 9501)

oregon <- gUnaryUnion(oregon.tract, id = oregon.tract@data$state)
d = oregon
npolygons = 1
for (selected_tract_index in selected_tract_indices){
d@polygons[[npolygons+1]] = oregon.tract@polygons[[selected_tract_index]]

npolygons = npolygons + 1
d@plotOrder=c(d@plotOrder,as.integer(npolygons))
}

plot(d)

Oregon with selected tract

The output of this operation is a SpatialPolygon. In case you want to convert it back to a SpatialPolygonDataDrame, here is a simple way to do it:

# Extract polygon ID's
( did <- sapply(slot(d, "polygons"), function(x) slot(x, "ID")) )

# Create dataframe with correct rownames
( d.df <- data.frame( ID=1:length(d), row.names = did) )    

# Try coersion again and check class
d <- SpatialPolygonsDataFrame(d, d.df)
class(d)