Using the stars
package, it is possible to the st_extract()
function to extract values from a raster at defined locations.
library(stars)
#> Loading required package: abind
#> Loading required package: sf
#> Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
tif <- system.file("tif/L7_ETMs.tif", package = "stars")
r <- read_stars(tif)
pnt <- st_sample(st_as_sfc(st_bbox(r)), 10)
st_extract(r[,,,1], pnt)
#> Simple feature collection with 10 features and 1 field
#> geometry type: POINT
#> dimension: XY
#> bbox: xmin: 288937.2 ymin: 9112173 xmax: 298589.9 ymax: 9120349
#> projected CRS: UTM Zone 25, Southern Hemisphere
#> L7_ETMs.tif geometry
#> 1 64 POINT (294613.4 9117565)
#> 2 72 POINT (295130 9117225)
#> 3 94 POINT (298589.9 9116806)
#> 4 86 POINT (296430.2 9112864)
#> 5 87 POINT (297481.9 9115176)
#> 6 110 POINT (288937.2 9112173)
#> 7 63 POINT (290966.6 9116890)
#> 8 84 POINT (295595.5 9116938)
#> 9 73 POINT (291047.1 9120349)
#> 10 65 POINT (294525.2 9117110)
What I would like to do is to use a buffer around these points and extract, let’s say, the mean
values inside a buffer.
Create buffers
poly <- st_buffer(pnt, dist = 100)
Now we have polygons
poly
#> Geometry set for 10 features
#> geometry type: POLYGON
#> dimension: XY
#> bbox: xmin: 288837.2 ymin: 9112073 xmax: 298689.9 ymax: 9120449
#> projected CRS: UTM Zone 25, Southern Hemisphere
#> First 5 geometries:
#> POLYGON ((294713.4 9117565, 294713.3 9117560, 2...
#> POLYGON ((295230 9117225, 295229.8 9117220, 295...
#> POLYGON ((298689.9 9116806, 298689.8 9116800, 2...
#> POLYGON ((296530.2 9112864, 296530.1 9112859, 2...
#> POLYGON ((297581.9 9115176, 297581.8 9115171, 2...
The problem is here, the st_extract()
function uses only points and not polygons.
st_extract(r[,,,1], poly)
#> Error in st_extract.stars(r[, , , 1], poly): all(st_dimension(pts) == 0) is not TRUE
Is there a way to extract information under polygons?
Created on 2021-02-19 by the reprex package (v1.0.0)