You could first use raster::clump()
to identify clusters of connected raster cells and then apply rasterToPolygons()
to "polygonize" those cells. (Do note, though, that each clump's area can be computed directly from the RasterLayer
without converting it to a SpatialPolygonsDataFrame
, as shown below):
library(rgeos) ## For the function gArea
## Clump and polygonize
Rclus <- clump(r)
SPclus <- rasterToPolygons(Rclus, dissolve=TRUE)
## Check that this works
plot(SPclus, col = seq_along(SPclus))
## Get cluster areas from RasterLayer object
transform(data.frame(freq(Rclus)),
area = count*prod(res(Rclus)))
## Get cluster areas from SpatialPolygons object
transform(data.frame(SPclus),
area = gArea(SPclus, byid=TRUE))