Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

up vote 10 down vote accepted

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')
share|improve this answer
    
thanks @Simbamangu - that worked. –  djq Dec 11 '11 at 19:45
    
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 4:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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