I am writing a function that expects two arguments: X and Y. Argument X should be a raster which can be generated by packages such as raster, terra, or stars.

Argument Y should be a polygon from packages such as sp or sf. All these packages manage spatial data differently and represent this data using objects of different structure.

How can I ensure that the user supplied objects of the right classes to my function?

Currently, I managed only to test whether object X is of class RasterLayer (created by the package raster) and whether the object Y is of class SpatialPolygonsDataFrame (created by the package sp)


  if(class(Y) != "SpatialPolygonsDataFrame"){
    stop("Y has to be a spatial object of type SpatialPolygonsDataFrame")
  if(class(X) != "RasterLayer"){
    stop("X has to be an object of class RasterLayer")
  • One efficient way to test for multiple classes is with any. Something along the lines of: if(!any(x %in% c("SpatRaster", "RasterLayer", "stars") ) you could then issue a stop as the condition. Oct 18, 2021 at 14:55
  • Sorry, answered on my phone, x should be wrapped in class. Oct 18, 2021 at 15:31

1 Answer 1


I'm doing pretty much the same

if (is(X, "RasterLayer") | is(X, "SpatRaster") | is(X, "stars"))
  # handle the different cases with specific code
  # personnally I convert to stars

if (is(X, "SpatialPolygonsDataFrame") | is(X, "sf"))
  # handle the different cases with specific code
  # personnally I convert to sf

In my case my code looks more like

if (inherit(X, "Spatial"))
  X <- sf::st_as_sf(X)

if (inherit(Y, "Raster"))
  Y <- stars::st_as_stars(Y)

if (inherit(Y, "SpatRaster"))
  Y <- stars::st_as_stars(Y) # that one does not exist do it yourself

if(!is(X, "sf"))
   stop("Y has to be a spatial object ")

if(!is(Y, "stars")
   stop("Y has to be a raster object")

geom = sf::st_geometry(X)

if (!is(geom, "sfc_POLYGON") & !is(geom, "sfc_MULTIPOLYGON"))
   stop("Y has to be a spatial polygon object ")

# keep going with sf/stars-based code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.