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)
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
R: How to Draw a Line with Multiple Arrows in It
How to Play Birthday Music Using R
How to Merge Two Columns in R with a Specific Symbol
Ggplot Geom_Point() with Colors Based on Specific, Discrete Values
Calculate Sum of a List of Variables by Group
Change Stringsasfactors Settings for Data.Frame
How to Make PDF Download in Shiny App Response to User Inputs
Matching Multiple Columns on Different Data Frames and Getting Other Column as Result
How to Change Font Family in a Legend in an R-Plot
How to Remove Na from Facet_Wrap in Ggplot2
Plot Random Effects from Lmer (Lme4 Package) Using Qqmath or Dotplot: How to Make It Look Fancy
How to Find Row Number of a Value in R Code
Clipping Raster Using Shapefile in R, But Keeping the Geometry of the Shapefile
Embedding a Miniature Plot Within a Plot
Colorize Parts of the Title in a Plot