Skip to content
Prev 10901 / 29559 Next

Help on extract function

On Sat, 12 Feb 2011, Sean O'Riordain wrote:

            
One of the major strengths of the raster package is that it encapsulates 
much of the lower-level detail that experienced users find in sp. So your 
main challenge is to read and understand ?extract. If your polygon(s) are 
smaller than the raster cells, you may need a different approach.

Understanding ?aggregate in base R may also help, because you do need to 
consider what to do with the multiple raster cell values that may lie 
within each polygon. Look carefully at the example at the foot of the help 
page:

library(raster)
r <- raster(ncol=36, nrow=18)
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 <- extract(r, polys)
str(v)
unlist(lapply(v, function(x) {
   if (!is.null(x)) mean(x, na.rm=TRUE) else NA
}))
v <- extract(r, polys, fun=mean, na.rm=TRUE)
v

So consider using the fun= argument to pass through an aggregation 
function. These aggregated values can next be made into a data frame, and 
polys promoted to a SpatialPolygonsDataFrame object, ready for writing as 
a shapefile.

It is important to understand that Spatial*DataFrame objects only look 
like shapefiles (or grids) to GIS-type people - to vanilla data analysts, 
they look like, smell like, and bark like data.frame objects (but have 
additional geometry things attached).

Hope this helps,

Roger