I’ve been doing a lot of analyses recently that need rasters representing features in the landscape. In most cases, these data have been supplied as shapefiles, so I needed to quickly extract parts of a shapefile dataset and convert them to a raster in a standardised format. Preferably with as little repetitive coding as possible. So I created a simple and relatively flexible function to do the job for me.
The function requires two main input files: the shapefile (
shp) that you want to convert and a raster that represents the background area (
mask.raster), with your desired extent and resolution. The value of the background raster should be set to a constant value that will represent the absence of the data in the shapefile (I typically use zero).
The function steps through the following:
- Optional: If
shpis not in the same projection as the
mask.raster, set the current projection (
proj.from) and then transform the shapefile to the new projection (
shpto a raster based on the specifications of
mask.raster(i.e. same extent and resolution).
- Set the value of the cells of the raster that represent the polygon to the desired
- Merge the raster with
mask.raster, so that the background values are equal to the value of
- Export as a tiff file in the working directory with the
labelspecified in the function call.
- If desired, plot the new raster using
- Return as an object in the global R environment.
The function is relatively quick, although is somewhat dependant on how complicated your shapefile is. The more individual polygons that need to filtered through and extracted, the longer it will take. Continue reading