[R-sig-Geo] Unexpected behaviour of "area" slot in sp Polygons
Gregory Duveiller
gduveiller at gmail.com
Mon Jan 26 16:19:49 CET 2015
Dear All,
I noticed something unusual when trying to get the areas of some polygons I
extracted from a raster.
In the script below, I generate a random raster with 4 classes, which I
then turn to a "SpatialPolygonsDataFrame". I then try to calculate areas
per class in two different ways.
########
require(sp)
require(raster)
require(rgeos)
nrows=100; ncols=100
rdum<-raster(nrows=nrows,ncols=ncols,xmn=0,ymn=0,ymx=100,xmx=100)
rdum[]<-round(runif(nrows*ncols,1,4))
vdum <- rasterToPolygons(rdum,dissolve=T)
# calculate areas
df <- data.frame(cls=1:4)
for(i in 1:4){
ddd <- sapply(vdum at polygons[[i]]@Polygons, function(x) x at area)
df$area1[i] <- sum(ddd)
df$area2[i] <- sum(as.vector(rdum==i))
}
#########
When I try to calculate the area per class from the attributes of the
Polygons, I do not always get the same number as when I simply count the
number of pixels of each class in the raster. In one iteration, for
example, I get the following number in which the areas in the Polygons is
higher by 52 units:
> df
cls area1 area2
1 1 1670 1670
2 2 3384 3352
3 3 3355 3335
4 4 1643 1643
Is there a reason one would not expect these to be always equal?
Thanks in advance...
Gregory Duveiller
[[alternative HTML version deleted]]
More information about the R-sig-Geo
mailing list