Clipping Raster Using Shapefile in R, But Keeping the Geometry of the Shapefile

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

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)

Sample Image

Clipping of raster as a shapefile in r

Crop, as stated in the manual pages, crops to the extent of the object,
for your purposes you may use raster::mask(), with the same syntaxis of crop
mask function "Creates a new Raster* object that has the same values as x, except for the cells that are NA (or other maskvalue) in a ’mask’."
You may pass inverse=T so you get those values out of the spatialPolygon.

R: Clip a shapefile boundary out of a generated image

Taken from http://leg.ufpr.br/geoR/tutorials/kc2sp.R:
You need to convert the kriging output to a Spatial object before you can pass it to mask(). The following should do it:

OK.pred<-krige.conv(gambling.geo,coords = gambling.geo$coords, data=gambling.geo$data, locations=grid,krige=krige.control(obj.model=gambling.vario.wls))
GT.s <- points2grid(SpatialPoints(as.matrix(grid)))
reorder <- as.vector(matrix(1:nrow(grid), nc=slot(GT.s, "cells.dim")[2])[,slot(GT.s, "cells.dim")[2]:1])
SGDF.s <- SpatialGridDataFrame(grid=GT.s, data=as.data.frame(OK.pred[1:2])[reorder,])
r<-raster(SGDF.s)
x<-mask(r, Macau)

Clipping rasters in R

The function crop in the raster package allows you to use an Extent object or an object for which an Extent can be calculated to cut(subset) another object. The package example:

r <- raster(nrow=45, ncol=90)
r[] <- 1:ncell(r)
e <- extent(-160, 10, 30, 60)
rc <- crop(r, e)

If you wanted to cut in a more detailed manner maybe you could use a SHP of the states and the over function in the sp package.



Related Topics



Leave a reply



Submit