[GIS] Remove certain polygon from SpatialPolygonDataFrame

rshapefilesp

I am using R maptools library to parse the shapefile into a list of polygons. The function readShapeSpatial

shp <- readShapeSpatial("<path to my shapefile>")

gives me a SpatailPolygonDataFrame object. In my example, my SpatialPolygonsDataFrame has the following columns:

> names(shp)
[1] "AREA"       "PERIMETER"  "COMAREA_"   "COMAREA_ID" "AREA_NUMBE"
[6] "COMMUNITY"  "AREA_NUM_1" "SHAPE_AREA" "SHAPE_LEN

I know that I can remove certain polygons by their row.id, e.g.

shp.dropI  <- shp[-i, ]
shp.subset <- shp[i %in% c(1,2,3),]

Now I want to drop certain polygon(s) with a condition, say AREA > 10. How do I implement this elegantly? The only method I have now is to iterate through all rows and find corresponding row.id.

Best Answer

First, I would highly recommend using readOGR, from the rgdal library, to read your shapefile. It will retain the projection information (proj4string) and save numerous headaches, when string matching, using other functions.

Two quick ways to accomplish what your are after are using an index or using subset. This will retain polygons with an area < 10 (dropping those > 10).

shp.sub <- shp[shp$AREA < 10,] 
shp.sub <- subset(shp, AREA < 10)
Related Question