exactextractr::exact_extract()
requires x
to be of type RasterLayer, RasterStack, RasterBrick or SpatRaster and y
of type sf, sfc, SpatialPolygonsDataFrame or SpatialPolygons. Basically, you can use {raster}
and {terra}
for raster data input and {sf}
and {sp}
for vector data.
Just like this:
library(terra)
#> terra 1.6.33
library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
library(geodata)
library(exactextractr)
# read raster
r <- rast("era5.temperature.19590106.nc")
r
#> class : SpatRaster
#> dimensions : 241, 281, 456 (nrow, ncol, nlyr)
#> resolution : 0.25, 0.25 (x, y)
#> extent : 69.875, 140.125, -0.125, 60.125 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84
#> source : era5.temperature.19590106.nc
#> varname : t (Temperature)
#> names : t_lev~100_1, t_lev~150_1, t_lev~200_1, t_lev~250_1, t_lev~300_1, t_lev~350_1, ...
#> unit : K, K, K, K, K, K, ...
#> time : 1959-01-06 00:00:00 to 1959-01-06 23:00:00 UTC
# subset to one layer, just for this demo
r_sub <- r["t_level=100_10"]
# get some random polygon vector for demonstration purposes
adm <- gadm("Cambodia", level = 0, path = tempdir()) |> sf::st_as_sf()
adm
#> Simple feature collection with 1 feature and 2 fields
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: 102.3338 ymin: 9.91361 xmax: 107.6277 ymax: 14.69027
#> Geodetic CRS: WGS 84
#> GID_0 COUNTRY geometry
#> 1 KHM Cambodia MULTIPOLYGON (((104.5359 10...
# extract and inspect
vals <- exact_extract(r_sub, adm)
head(vals[[1]])
#> value coverage_fraction
#> 1 193.1998 0.0369466245
#> 2 193.1374 0.1065797433
#> 3 193.2218 0.0737281293
#> 4 193.3062 0.0003664213
#> 5 193.3852 0.0259982608
#> 6 193.4476 0.0130981132
Created on 2022-11-06 with reprex v2.0.2
map
object here?ncdf4
library before reading the NetCDF file? Why are you ignoring the warning coming fromraster::stack
? Your problem is not withexact_extract
but, coming from an incorrect read of the source file. Admittedly, it is not clear thatncdf4
is required for correct import of cdf files but this is, in fact, the case. Alternately, you could try this using the terra library withterra::rast
to see if this mitigates the cdf import.