Combining polygons and calculating their area (i.e. number of cells) in R

风流意气都作罢 提交于 2019-12-04 03:24:10

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))

The rgeos package has many polygon manipulation tools. gUnion will union together touching polygons:

require(rgeos)
uni <- gUnion( r_poly , r_poly )
plot( uni , col = 2 )

Robert Hijmans

rasterToPolygons() is a computationally very expensive operation so, assuming the CRS is planar, I would go for:

m <- clump(r)
f <- freq(m)
f[,2] <- f[,2] * xres(r) * yres(r) 

For lon/lat, I would use:

a <- area(r)
zonal(a, m, 'sum') 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!