[R-sig-Geo] Combining polygons and calculating their area (i.e. number of cells)

Roger Bivand Roger.Bivand at nhh.no
Thu Dec 19 13:23:40 CET 2013


On Wed, 18 Dec 2013, Josh O'Brien wrote:

> This is cross-posted from StackOverflow
> (http://stackoverflow.com/questions/20659186/combining-polygons-and-calculating-their-area-i-e-number-of-cells-in-r),
> where it has received an answer that I believe answers both questions.
>

Because of the forking to SO, the code now displayed is suboptimal. 
Developers not interested in (or simply irritated by) gamifying are not 
going to waste time on SO, OK?

The last block concludes with:

## Get cluster areas from SpatialPolygons object
transform(data.frame(SPclus),
           area = sapply(SPclus at polygons, function(X) X at area))

and @JoshO'Brien commented: "However, I discovered that the last part of 
the R-code (i.e Get cluster areas from SpatialPolygons object) was not 
always working properly. Interestingly, (sometimes) the area of the 
largest cluster from the SpatialPolygons object was overestimated"

This is documented in:

library(sp)
?"Polygons-class"

and in Bivand et al. (2013) pp. 41-44; the area values are an adjunct 
to plotting polygons in the largest to smallest order to prevent small 
polygons being overpainted on some devices. If you want the area of a 
Polygons object, use rgeos::gArea(SPclus, byid=TRUE).

By the way, always avoid accessing S4 objects directly using @, do use 
slot(obj, "slotname") - the sapply should read:

area = sapply(slot(SPclus, "polygons"), slot, "area")

for the SO version with possibly incorrect areas, and

area = gArea(SPclus, byid=TRUE)

for correct ones. Finally, never use T/F for TRUE and FALSE, try:

T <- FALSE

and TRUE <- FALSE

and see the difference.

Terminally uninterested in winning points on SO,

Roger

>
>
> --
> View this message in context: http://r-sig-geo.2731867.n2.nabble.com/Combining-polygons-and-calculating-their-area-i-e-number-of-cells-tp7585395p7585401.html
> Sent from the R-sig-geo mailing list archive at Nabble.com.
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Department of Economics, Norwegian School of Economics,
Helleveien 30, N-5045 Bergen, Norway.
voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-sig-Geo mailing list