isciences / exactextractr

R package for fast and accurate raster zonal statistics
https://isciences.gitlab.io/exactextractr/
272 stars 26 forks source link

"weighted_mean" yields the error "Incompatible extents" #77

Closed Kodiologist closed 11 months ago

Kodiologist commented 2 years ago

Here's my attempt at a simple example in the style of vig1_population:

crs.lonlat = 4326 # https://epsg.io/4326

pop.density = raster::raster("pop-density-2015.tiff")
  # From https://sedac.ciesin.columbia.edu/downloads/data/gpw-v4/gpw-v4-population-density-rev11/gpw-v4-population-density-rev11_2015_30_sec_tif.zip

polygons = sf::read_sf("/vsizip/us.zip")
  # From https://www2.census.gov/geo/tiger/GENZ2019/shp/cb_2019_us_state_500k.zip
polygons = sf::st_transform(crs = crs.lonlat,
    polygons[polygons$STUSPS %in% c("NY", "NJ", "PA"),])

test.values = raster::rasterFromXYZ(crs = crs.lonlat, transform(
    with(as.list(sf::st_bbox(polygons)), expand.grid(
        x = seq(xmin - 1, xmax + 1, len = 10),
        y = seq(ymin - 1, ymax + 1, len = 10))),
    z = x^2 + y^2))

x = exactextractr::exact_extract(
    test.values, polygons,
    fun = 'weighted_mean', weights = pop.density)

The result is Error in CPP_stats(x, weights, wkb, default_value, default_weight, coverage_area, : Incompatible extents.. Why are the extents incompatible? I'm not sure if I'm doing something wrong or there's a bug. I tried cropping pop.density, since the GPW raster in the vignette is cropped, but the error persisted. I started out using terra rather than raster, but switching to raster didn't help.

I'm using exactextractr 0.8.2, sf 1.0.7, and raster 3.5.15 on R 4.1.2.

dbaston commented 2 years ago

The error message could be more helpful. Here's the definition of "compatible" from the README:

The weighting raster must use the same coordinate system as the primary raster, and it must use a grid that is compatible with the primary raster. (The resolutions and extents of the rasters need not be the same, but the higher resolution must must be an integer multiple of the lower resolution, and the cell boundaries of both rasters must coincide with cell boundaries in the higher-resolution grid.)

Kodiologist commented 2 years ago

I see. I missed that. I guess using the GPW raster directly as weights isn't an option for value rasters that are on a grid too different from that of GPW, at least without regridding one or the other. Thanks.