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

后端 未结 1 2465
-上瘾入骨i
-上瘾入骨i 2020-12-13 10:34

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

相关标签:
1条回答
  • 2020-12-13 11:06

    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

    0 讨论(0)
提交回复
热议问题