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.

djq
  • 16,297
  • 31
  • 110
  • 182

1 Answers1

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')
djq
  • 16,297
  • 31
  • 110
  • 182
Simbamangu
  • 14,773
  • 6
  • 59
  • 93
  • Saw your edit and checked again - the final forward slash is apparently optional on OSX, I take it not with Windows? Worth knowing! – Simbamangu Dec 12 '11 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 Dec 12 '11 at 15:30
  • OSX 10.7.2 / R 2.14 on mine; definitely works either way 'round. What are you using? – Simbamangu Dec 13 '11 at 04:14
  • 1
    To automatize conversion, I wrote this: https://github.com/brry/misc/blob/master/shp2raster.R – Berry Nov 25 '16 at 10:50