[GIS] Eliminating small polygons from shapefile after polygonize in R

rshapefile

I have a shapefile "shape_clara" that was polygonized using function rasterToPolygons(x, dissolve=TRUE). But then I have multipolygons for each class, and I want to eliminate the small polygons by area. So I have to access each polygon inside the multipolygon.

I did that:

listao<-list()
for (j in 1:length(shape_clara@polygons)){
lista<-vector()
for (i in 1:length(shape_clara@polygons[[j]]@Polygons)){
if (shape_clara@polygons[[j]]@Polygons[[i]]@area<50000) lista<-rbind(lista,i)
}
listao[[j]]<-lista
}

Ok so far, listao give me all the small polygons ID.

And then to remove the small polygons:

for (i in length(shape_clara@polygons)){
shape_clara@polygons[[i]]@Polygons<-shape_clara@polygons[[i]]@Polygons[-as.vector(listao[[i]])]
}

But when I look the result, they are still there.

Any tips about how to remove them?

Best Answer

I approached a similar problem using this function:

AreaPercent <- function(x) { tot_area <- sum(sapply(slot(x, "polygons"), slot, "area")) sapply(slot(x, "polygons"), slot, "area") / tot_area * 100

And then:

shape_clara[AreaPercent(shape_clara) > 5,]

Obviously my function using an area percent rather than specific size, but could be adapted I think to your situation? You might also have a look at rmapshaper (https://cran.r-project.org/web/packages/rmapshaper/vignettes/rmapshaper.html) and functionality in simple features (http://r-spatial.org/r/2017/03/19/invalid.html).

Related Question