rrasterterra

R - error with terra::extract : unable to find inherited method for function "extract" for signature "SpatRaster", "SpatialPolygons"


I'm trying to convert an R script using package raster in order to use package terra instead. So I changed the raster::raster function for terra::rast function, and also the raster::extract for terra::extract function.

Reproducible example :

cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))

polys <- SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1)))
exo <- rast(cds2) #normally a .tiff file here.

val <- terra::extract(exo, polys)

I get the following error : Error in (function (classes, fdef, mtable) : unable to find inherited method for the function ‘extract’ for signature ‘"SpatRaster", "SpatialPolygons"’

How can I fix the error and extract the values from exo without using raster package in the script ?

Thanks for your answers.


Solution

  • The error message is:

    Error in (function (classes, fdef, mtable)  :  
    unable to find inherited method for the function ‘extract’
     for signature ‘"SpatRaster", "SpatialPolygons"’
    

    And if you look at ?terra::extract you can see that there is a method for

    "SpatRaster", "SpatVector"
    

    So you need to represent your polygons as a SpatVector. You can do:

    val <- terra::extract(exo, vect(polys))
    

    And in real life you could probably do something like this

    polys <- vect("filename.shp")
    val <- terra::extract(exo, polys)
    

    The bottom line is that if you want to use "terra" instead of the obsolete "raster" package, you should not be using the "sp" package to represent vector data.