In this question an stars object is masked with a raster object. But it is not clear to me how the masking can be done with a vector object using the stars pkg.

Consider the following example in terra.

I want to mask srtm with zion:


#   SpatRaster class from terra
srtm = rast(system.file("raster/srtm.tif", package = "spDataLarge"))

#   sf class from sf
zion = read_sf(system.file("vector/zion.gpkg", package = "spDataLarge"))
zion = st_transform(zion, crs(srtm))

#   Transforming sf class to SpatVector class from terra
zion_vect = vect(zion)

#   Masking in terra
srtm_masked = mask(srtm, zion_vect)

This produces the desired result enter image description here

The stars documentation here says that mask in the raster package can be done as [] <- in stars, but using this with a sf object raises an error.

Converting strm to an stars object, srtms = st_as_stars(srtm), and executing

srtms_masked <- srtms
srtms_masked[zion] <- srtms

I get an error

Error in `[<-.stars`(`*tmp*`, zion, value = list(srtm.tif = c(1728, 1718,  : 
  selector should be a stars object

So, I am not sure what [] <- means for masking with vector layer.

In particular, I’m looking for the translation of

## S4 method for signature 'SpatRaster,SpatVector'
mask(x, mask, inverse=FALSE, updatevalue=NA,
    touches=TRUE, filename="", ...)

from terra to stars, where the touches option can be important.

  • Can you edit your question to create some sample objects for this? So you can then say "I want to mask this x with this y" without us having to create our own x and y. Will save us a bit of trouble and make your question more likely to be answered.
    – Spacedman
    Commented Jul 24, 2022 at 8:40
  • Done it! Completely rewritten, with an example. Commented Jul 25, 2022 at 8:52
  • Am not sure the docs are right so opened an issue: github.com/r-spatial/stars/issues/550
    – Spacedman
    Commented Jul 25, 2022 at 10:40

1 Answer 1


Converting your terra object to stars and then subsetting by your sf zion object seems to work:

srtms = st_as_stars(srtm)

You never actually gave the line of code you said didn't work, but said something about [] <- which would be some kind of replacement operation. Anyway, the expression srtms[zion] returns a masked stars object.

enter image description here

Weirdly the documentation seems to imply that this should be an "extract" operation, returning the values of the raster in the polygon, but it doesn't do that.

enter image description here

  • Thanks for the issue and the help. I have added to the main question the line of code that gave me an error. Also it is not clear how the masked object, srtms[zion], handles the border cells, the touches option in maks. Commented Jul 25, 2022 at 15:22

Your Answer

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

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