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.
Answer
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')
No comments:
Post a Comment