stars icon indicating copy to clipboard operation
stars copied to clipboard

Does `stars_object[sf_polygons]` mask or extract?

Open barryrowlingson opened this issue 3 years ago • 3 comments

If I do srtms[zion] where:

> srtms
stars object with 2 dimensions and 1 attribute
attribute(s):
      Min. 1st Qu. Median     Mean 3rd Qu. Max.
srtm  1024    1535   1837 1842.548    2114 2892
dimension(s):
  from  to  offset        delta refsys point values x/y
x    1 465 -113.24  0.000833333 WGS 84 FALSE   NULL [x]
y    1 457 37.5129 -0.000833333 WGS 84 FALSE   NULL [y]
> zion
Simple feature collection with 1 feature and 11 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: -113.2283 ymin: 37.14135 xmax: -112.8631 ymax: 37.50428
Geodetic CRS:  WGS 84
# A tibble: 1 × 12
  UNIT_CODE GIS_Notes       UNIT_NAME  DATE_EDIT  STATE REGION GNIS_ID UNIT_TYPE
* <chr>     <chr>           <chr>      <date>     <chr> <chr>  <chr>   <chr>    
1 ZION      Lands - http:/… Zion Nati… 2017-06-22 UT    IM     1455157 National…
# … with 4 more variables: CREATED_BY <chr>, METADATA <chr>, PARKNAME <chr>,
#   geom <POLYGON [°]>

I get the stars object masked by the polygon. But the docs for stars equivs of raster functionality: https://r-spatial.github.io/stars/articles/stars6.html says that's "extract (by polygon)" which (in terra anyway) gets the values of cells in the raster and is so used for things like average value over a polygon.

Those docs give [] <- as the stars equivalent for mask, but attempts to use that fail, and I can't think how it would work anyway. Maybe this would set all inside zion to 1?

srtms[zion]=1 Error in [<-.stars(*tmp*, zion, value = 1) : selector should be a stars object

Reproducible example and source query via GIS.stacko https://gis.stackexchange.com/questions/436707/mask-a-raster-stars-object-in-r-with-a-vector-sf-object

barryrowlingson avatar Jul 25 '22 10:07 barryrowlingson

Thanks, I hope this clarifies more.

edzer avatar Aug 08 '22 15:08 edzer

Not completely (at least for me):

  1. What happens with border cells (cells intersecting the polygon boundaries)? Are they included or excluded in masking? This relates to the touches=T/F option in mask (terra).
  2. The documentation still says that x[sf_object] performs an extraction operation, that in raster/terra refers to getting the values of the raster, but in fact returns a masked stars object.

Thanks a lot.

fgoerlich avatar Aug 13 '22 20:08 fgoerlich

See section subsetting here which shows that by default the cells with cell center intersecting the geometry are selected. However (read ?st_crop) when you want all cells touched then use as_points = FALSE

plot(x[circle,as_points=FALSE][, , , 1], reset = FALSE)
plot(circle, col = NA, border = 'red', add = TRUE, lwd = 2)

x

edzer avatar Aug 16 '22 19:08 edzer