Take a look at the help, the rasterize
function in raster will, in fact, accept a SpatialPolygonsDataFrame
.
Adapted from the second polygon example in rasterize
help.
Create polygon examples
library(raster)
polys <- spPolygons(rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)),
rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)),
rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0)),
rbind(c(-180,10), c(0,90), c(40,90), c(145,-10),
c(-25, -15), c(-180,0), c(-180,10)))
Coerce to SpatialPolygonsDataFrame and add data
polys <- as(polys, "SpatialPolygonsDataFrame")
polys@data[,1] <- runif(nrow(polys))
class(polys)
Now, rasterize the polygon data and plot. The r
raster is the reference raster for the rasterize function.
r <- raster(ncol=90, nrow=45)
r.polys <- rasterize(polys, r, field = polys@data[,1], fun = "mean",
update = TRUE, updateValue = "NA")
plot(r.polys)
One thing that I noticed is that at raster 2.4-30 under windows with R 3.2.3 the "field" argument is not recognizing the column index (eg., field = 1). However, if I pass the argument the actual vector (as in my example) then it assigns the correct values to the resulting raster for all of the polygons. This can easily be recreated, with the example, using the syntax:
r.polys <- rasterize(polys, r, field = 1, fun = "mean", update = TRUE, updateValue = "NA")`