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)
此操作的输出结果是一个SpatialPolygon。如果您想将其转换回SpatialPolygonDataDrame,这里有一种简单的方法:
# 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)