Extract Raster from Raster using Polygon shapefile in R
The extract function is behaving exactly as it should. You can force the crop function to use the extent of the polygon and then mask the object to return the exact raster representing the polygon area. If you continue to receive the error it means that your data, in fact, does not overlap.
Please keep in mind that R does not perform "on the fly" projection so, check your projections. You can check if your extents overlap using the "extent()" function.
Here is an example of cropping using the polygon extent then masking the resulting raster using the "rasterized" polygon.
# Add required packages
require(raster)
require(rgeos)
require(sp)
# Create some data using meuse
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
gridded(meuse.grid) = TRUE
r <- raster(meuse.grid)
r[] <- runif(ncell(r))
# Create a polygon
f <- gBuffer(meuse[10,], byid=FALSE, id=NULL, width=250,
joinStyle="ROUND", quadsegs=10)
# Plot full raster and polygon
plot(r)
plot(f,add=T)
# Crop using extent, rasterize polygon and finally, create poly-raster
# **** This is the code that you are after ****
cr <- crop(r, extent(f), snap="out")
fr <- rasterize(f, cr)
lr <- mask(x=cr, mask=fr)
# Plot results
plot(lr)
plot(f,add=T)
What I actually searched for was the mask()
function.
mask(raster, poly_shape)
works without errors and returns what I searched for.