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)

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.

  • Be wary of "AREA" attributes. There's no guarantee that's the actual area, right? You can use rgeos::gArea(x, byid = TRUE) to calculate it, and rgdal::spTransform if you need to change projection for that calculation.
    – mdsumner
    Mar 1 '16 at 23:01
  • @mdsumner you are completely right. Good point Mar 1 '16 at 23:39

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)
  • Nice! I just realized this question could be generalized into "how to select certain rows in DataFrame with R". And thanks for the suggestion too Mar 1 '16 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.