How to rasterize an object of class SpatialPolygonsDataframe in R

When I read a polygon shapefile into R using rgdal, it was imported as an object of classSpatialPolygonsDataframe.

I need to rasterize the polygon, but therasterize{raster}function requires it to be of theSpatialPolygonsclass.

How do I convert it from the current data frame into theSpatialPolygonsclass?

Take a look at the help, therasterizefunction in raster will, in fact, accept aSpatialPolygonsDataFrame.

Adapted from the second polygon example inrasterizehelp.

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") [email protected][,1] <- runif(nrow(polys)) class(polys)

Now, rasterize the polygon data and plot. Therraster is the reference raster for the rasterize function.

r <- raster(ncol=90, nrow=45) r.polys <- rasterize(polys, r, field = [email protected][,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")'

Watch the video: Buffer ArcGIS - ArcGIS Buffer Analysis - Arcmap Tutorial For Beginners (October 2021).