raster (version 1.1.7)

polygonValues: Extract values from a RasterLayer by polygons

Description

This method returns the values of the cells of a Raster object that is covered by a polygon. A cell is covered if its center is inside the polygon (but see the weights option for considering partly covered cells).

Usage

polygonValues(p, r, ...)

Arguments

p
SpatialPolygons* object
r
Raster object
...
additional arguments. See details

Value

  • a list as long as the number of polygons in p

Details

There are two related additional arguments: weights. If TRUE, the function returns, for each polygon, a matrix with the cell values and the approximate fraction of each cell covered (rounded to 1/100; and the sum of weights should be ~1. 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.

See Also

cellValues, xyValues, getValues, SpatialPolygons

Examples

Run this code
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 DataCamp Workspace