19

I'm trying to convert a shapefile into a raster within R. My approach is to read in the raster as follows:

library(rgdal) # Loads SP package by default
demo <- readOGR('F:/data/', 'shapefile') # Creates a SpatialPolygonsDataFrame class (sp)

This works fine, and I can plot it. However it is a large shapefile and I want to convert it into a raster. I've tried the following:

r <- raster(ncol=180, nrow=180)
Demo_ras = rasterize(r, demo, 'pop')  # pop is an integer here

Error message:

Error in function (classes, fdef, mtable)  : 
  unable to find an inherited method for function "rasterize", for signature "RasterLayer", "SpatialPolygonsDataFrame"

I'm slightly confused which is the correct order of the arguments. I've also tried this:

Demo_ras = rasterize(demo, r, 'pop')

Which results in the follow error:

Error in .polygonsToRaster(x, y, ...) : 
  polygon and raster have no overlapping areas

While it makes sense that a raster cannot be generated for an area that does not cover the SpatialPolygonsDataFrame, I'm not sure what information I need to specify so that the raster should contain the SpatialPolygonsDataFrame area.

1 Answer 1

25

The rasterize() function wants to have the shape (polygon) first then the raster by default, hence your first error. The second command you've shown Demo_ras = rasterize(demo, r, 'pop') is the correct way around, but as you discovered it needs the extents to match!

You can assign the extents of the raster to cover the same extents of the polygon:

extent(r) <- extent(demo)

... this should work for the example you've provided, as long as 'pop' is the correct name of a variable in 'demo'. The following worked just now (R 2.14 / OSX), where AREA is a real number column in boundary.shp:

poly <- readOGR("/workingdirectory", "boundary") # does not work  with final slash '/' 
r <- raster(ncol=180, nrow=180)
extent(r) <- extent(poly)
rp <- rasterize(poly, r, 'AREA')
4
  • Saw your edit and checked again - the final forward slash is apparently optional on OSX, I take it not with Windows? Worth knowing!
    – Simbamangu
    Commented Dec 12, 2011 at 10:54
  • hmmm, I had a problem with the slash on both OSX and Windows.. not sure if we are using the same version or not.
    – djq
    Commented Dec 12, 2011 at 15:30
  • OSX 10.7.2 / R 2.14 on mine; definitely works either way 'round. What are you using?
    – Simbamangu
    Commented Dec 13, 2011 at 4:14
  • 1
    To automatize conversion, I wrote this: github.com/brry/misc/blob/master/shp2raster.R
    – Berry
    Commented Nov 25, 2016 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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