3

I'm trying to convert several shapefiles in rasters at the same time. I already was able to read the shapefiles by doing this:

library(maptools)

shps <- dir(getwd(), "*.shp")
for (shp in shps) assign(shp, readShapePoly(shp))
for(j in 1:245)
{
New<-readShapePoly(shps[j])     
}

But now, I don't know how to convert these to raster and then plotting it. I tried the commands on this page, but I only obtain errors

1 Answer 1

2

Here is a short example using Tanzanian administrative data obtained from DIVA-GIS. I am using lapply to loop through all layers, readOGR from the rgdalpackage to import the single shapefiles and rasterize from the raster package to perform the conversion. Make sure to set up a template, otherwise you won't be able to convert the shapefiles.

# Required packages
library(rgdal)
library(raster)

# Loop through single layers
adm <- lapply(c("TZA_adm0", "TZA_adm1", "TZA_adm2", "TZA_adm3"), function(i) {
  # Import shapefile
  shp <- readOGR("data", i)
  # Create raster template
  template <- raster(ext = extent(shp), crs = projection(shp))
  # Rasterize shapefile
  rst <- rasterize(shp, template, field = "Shape_Area")
})

Don't forget to adjust the field argument in the rasterize function to your personal needs. Here's what we end up with (well, the plot doesn't really make sense, but the end justifies the means, right? ;-)).

plot(adm[[2]], xlab = "lon", ylab = "lat", main = "Shape_Area_adm1")

Level 2 administrative boundaries of Tanzania

Hope this helps,
Cheers!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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