Search code examples
rgeospatialrastershapefile

I have problems to clip a raster from a polygon in R


I'm trying to clip a raster file using a polygon as a base. However I have the same error. I provided a example below:

I'm trying to clip a raster file using a polygon as a base. However I have the same error. I provided a example below:

First, I define the polygon.

Here is the polygon

library(maptools)
data("wrld_simpl")
cl<-subset(wrld_simpl, NAME=="Chile") 
plot(cl)

Then I set the raster file

library(geodata)
foot_p<-footprint(year = 2009, path = "data/")
plot(foot_p)

I tried to clip the raster with crop function

foot.cl<-crop(foot_p, cl)

However, its seem to only clip the extent of it, and I need to clip the raster inside the polygon borders. I was tried using mask function, but I hace the error

foot.cl2<-mask(foot.cl, cl) 

but I have the error

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘mask’ for signature ‘"SpatialPolygonsDataFrame", "SpatRaster"’

I think could be the CRS between data

>foot.cl
class       : SpatialPolygonsDataFrame 
features    : 1 
extent      : -109.4492, -66.42056, -55.9175, -17.50528  (xmin, xmax, ymin, ymax)
crs         : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs 
variables   : 11
names       : FIPS, ISO2, ISO3,  UN,  NAME,  AREA,  POP2005, REGION, SUBREGION,     LON,     LAT 
value       :   CI,   CL,  CHL, 152, Chile, 74880, 16295102,     19,         5, -69.433, -23.389 
> foot.cl
class       : SpatRaster 
dimensions  : 4609, 5164, 1  (nrow, ncol, nlyr)
resolution  : 0.008333333, 0.008333333  (x, y)
extent      : -109.45, -66.41667, -55.91667, -17.50833  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source(s)   : memory
varname     : wildareas-v3-2009-human-footprint_geo 
name        : wildareas-v3-2009-human-footprint 
min value   :                                 0 
max value   :                 

Any thoughts??, thank you every one

R.


Solution

  • You get this error

    unable to find an inherited method for function ‘mask’ for signature ‘"SpatialPolygonsDataFrame", "SpatRaster"’

    Because there is a mask method for Raster* and SpatialPolygons* objects, but not for SpatRaster and SpatialPolygons. See ?mask It is best to move away from the old raster and sp packages, and especially maptools as this package is not on CRAN anymore.

    You can do

    library(geodata)
    library(terra)
    foot_p <- geodata::footprint(year = 2009, path = "data/")
    chl <- geodata::gadm("Chile", level=1, path="data/")
    
    foot.cl <- crop(foot_p, chl, mask=TRUE)
    plot(foot.cl)
    

    But apporach should also work if you do

    foot.cl2 <- mask(foot.cl, vect(cl))