3

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

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

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

  • See my answer for rasterizing your polygons, but theanswer to your coercion question is to use the "as" method. polys <- as(polys, "SpatialPolygons") – Jeffrey Evans Jan 5 '16 at 22:39
8

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")`      

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.