weights
option for considering partly covered cells).polygonValues(p, x, ...)
weights
. If TRUE
, the function returns, for each polygon, a matrix with the cell values and the approximate fraction of each cell that is covered by the polygon(rounded to 1/100). The weights can be used for averaging; see examples. This option can be useful if the polygons are small relative to the cells size of the RasterLayer
cellnumbers
. If cellnumbers=TRUE
and weights=TRUE
, cellnumbers will also be returned.cellValues
, xyValues
, getValues
, SpatialPolygons
r <- raster(nrow=18, ncol=9)
r[] <- 1:ncell(r)
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
polys <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), Polygons(list(Polygon(cds2)), 2)))
#plot(r)
#plot(polys, add=TRUE)
v <- polygonValues(polys, r)
v
# mean for each polygon
unlist(lapply(v, function(x) if (!is.null(x)) mean(x, na.rm=TRUE) else NA ))
# v <- polygonValues(polys, r, weights=TRUE)
# v
## weighted mean for each polygon
# unlist(lapply(v, function(x) if (!is.null(x)) {sum(apply(x, 1, prod)) / sum(x[,2])} else NA ))
Run the code above in your browser using DataLab