isciences / exactextractr

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

weighted.mean does not work with raster stacks/bricks #54

Closed lucas-johnson closed 3 years ago

lucas-johnson commented 3 years ago

Description

weighted.mean fails with raster stacks. I followed the example here hoping to extract the mean, but return NA if any of of the cells are NA. Essentially I wanted to use the mean function with na.rm = F. And I thought weighted.mean was the best way to do that. Unfortunately it doesn't seem to work with raster stacks...Is there a better way to do this?

Reprex:

library(exactextractr)
library(sf)
#> Warning: package 'sf' was built under R version 4.0.2
#> Linking to GEOS 3.8.1, GDAL 3.1.4, PROJ 6.3.1
library(raster)
#> Warning: package 'raster' was built under R version 4.0.2
#> Loading required package: sp
#> Warning: package 'sp' was built under R version 4.0.2
make_rect <- function(xmin, ymin, xmax, ymax, crs) {
  sf::st_sfc(
    sf::st_polygon(
      list(
        matrix(
          c(xmin, ymin,
            xmax, ymin,
            xmax, ymax,
            xmin, ymax,
            xmin, ymin),
          ncol=2,
          byrow=TRUE))),
    crs=crs)
}
data <- matrix(1:100, nrow=10, byrow=TRUE)
data[7:10, 1:4] <- NA # cut out lower-left corner
rast <- raster::raster(
  data,
  xmn=0, xmx=10, ymn=0, ymx=10,
  crs='+proj=longlat +datum=WGS84'
)
rast_brick <- brick(rast, rast)
square <- make_rect(3.5, 3.5, 4.5, 4.5, sf::st_crs(rast))
exact_extract(rast, square, weighted.mean)
#> [1] NA
exact_extract(rast_brick, square, weighted.mean, stack_apply = T)
#> Error in weighted.mean.default(vals, cov_fracs, ...): 'x' and 'w' must have the same length
dbaston commented 3 years ago

This example works on for me on the development version, which I am submitting to CRAN this morning. Can you let me know what version you have installed?

lucas-johnson commented 3 years ago
packageVersion("exactextractr")
#> [1] '0.5.0'
dbaston commented 3 years ago

This is also working as expected for me on version 0.5.0, so I'm not quite sure what's going on. Version 0.6.0 is now on CRAN - could you give that a try?

lucas-johnson commented 3 years ago

Version 0.6.0 works! Thank you!