Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shapefile to raster conversion in R?

I have a shapefile downloaded from the worldwildlife.org for the terrestrial ecoregions of the world. The file can be loaded here: http://worldwildlife.org/publications/terrestrial-ecoregions-of-the-world.

It comes as a standard shape file and I would like to do two things with it. First: take the shapefile from my local directory and clip it to an extent of eastern North America (ext= extent (-95, -50, 24, 63))

# Read shapefile using package "maptools"
eco_shp <- readShapeLines("F:/01_2013/Ecoregions/Global/wwf_terr_ecos.shp", 
                          proj4string=CRS("+proj=utm +zone=33 +datum=WGS84")) 


# Set the desired extent for the final raster using package "raster" 
ext <- extent(-95, -50, 24, 63)

I am sure I have to use the rasterize function in the package "raster" but I am still not able to get it work correctly. I would appreciate any suggestions on how to do this.

like image 606
I Del Toro Avatar asked Feb 20 '13 23:02

I Del Toro


People also ask

Can you turn a shapefile into a raster?

Any feature class (geodatabase, shapefile, or coverage) containing polygon features can be converted to a raster dataset. The input field type determines the type of output raster. If the field is integer, the output raster will be integer; if it is floating point, the output will be floating point.

Can R read shapefiles?

Read it with rgdalThe rgdal package offers the readOGR() function that allows to read shapefile using the following syntax. As a result you get a geospatial object ( my_spdf here) that contains all the information we need for further mapping.


1 Answers

You are right to think that you should be using raster (rather than the sp raster Spatial classes) for spatial raster data. You should also use rgdal (rather than maptools) for reading, writing, and otherwise manipulating spatial vector data.

This should get you started:

library(rgdal)
library(raster)

## Read in the ecoregion shapefile (located in R's current working directory)
teow <- readOGR(dsn = "official_teow/official", layer = "wwf_terr_ecos")

## Set up a raster "template" to use in rasterize()
ext <-  extent (-95, -50, 24, 63)
xy <- abs(apply(as.matrix(bbox(ext)), 1, diff))
n <- 5
r <- raster(ext, ncol=xy[1]*n, nrow=xy[2]*n)

## Rasterize the shapefile
rr <-rasterize(teow, r)

## A couple of outputs
writeRaster(rr, "teow.asc")
plot(rr)

enter image description here

like image 147
Josh O'Brien Avatar answered Sep 22 '22 02:09

Josh O'Brien