Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipping raster using shapefile in R, but keeping the geometry of the shapefile

Tags:

I am using {raster} to clip (or crop) a raster based on an irregular shapefile (the Amazon biome) but the output always has a rectangular extent. However, I need the output in the exact same geometry of the shapefile. Any tips? Cheers.

library(raster) library(rgdal)  myshp <- readOGR("Amazon.shp", layer="Amazon") e <- extent(myshp) myraster <- raster("Temperature.tif") myraster.crop <- crop(myraster, e, snap="out", filename="myoutput.tif") 
like image 685
ALS.Meyer Avatar asked Apr 15 '14 02:04

ALS.Meyer


People also ask

Can I clip a raster with a polygon?

The Clip button on the Image Analysis window provides the functionality to clip any raster including a grid using a selected polygon feature within a feature class layer.

Can you clip a raster?

An existing raster or vector layer can be used as the clip extent. If you are using a feature class as the output extent, you can clip the raster by the minimum bounding rectangle of the feature class or by the polygon geometry of the features.


1 Answers

One option is to use raster::mask()

library(maptools)  ## For wrld_simpl library(raster)  ## Example SpatialPolygonsDataFrame data(wrld_simpl) SPDF <- subset(wrld_simpl, NAME=="Brazil")  ## Example RasterLayer r <- raster(nrow=1e3, ncol=1e3, crs=proj4string(SPDF)) r[] <- 1:length(r)  ## crop and mask r2 <- crop(r, extent(SPDF)) r3 <- mask(r2, SPDF)  ## Check that it worked plot(r3) plot(SPDF, add=TRUE, lwd=2) 

enter image description here

like image 58
Josh O'Brien Avatar answered Oct 03 '22 18:10

Josh O'Brien