Giter Club home page Giter Club logo

exactextractr's Introduction

exactextractr

Build Status coverage report CRAN cran checks

exactextractr is an R package that quickly and accurately summarizes raster values over polygonal areas, commonly referred to as zonal statistics. Unlike most zonal statistics implementations, it handles grid cells that are partially covered by a polygon. Despite this, it performs faster other packages for many real-world applications.

Example Graphic.

Calculations are performed using the C++ exactextract tool. Additional background and a description of the method is available here. Full package reference documentation is available here.

Basic Usage

The package provides an exact_extract method that operates analogously to the extract method in the raster package. The snippet below demonstrates the use of this function to compute monthly mean precipitation for each municipality in Brazil.

library(raster)
library(sf)
library(exactextractr)

# Pull municipal boundaries for Brazil
brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

# Pull gridded precipitation data
prec <- getData('worldclim', var='prec', res=10)

# Calculate vector of mean December precipitation amount for each municipality
brazil$mean_dec_prec <- exact_extract(prec[[12]], brazil, 'mean')

# Calculate data frame of min and max precipitation for all months
brazil <- cbind(brazil, exact_extract(prec, brazil, c('min', 'max')))

Summary Operations

exactextractr can summarize raster values using several named operations as well as arbitrary R functions. Where applicable, a named operation will provide better performance and reduced memory usage relative to an equivalent R function. Named operations are specified by providing a character vector with one or more operation names to the fun parameter of exact_extract.

The following summary operations are supported:

Name Description
count Sum of all cell coverage fractions.
majority (or mode) The raster value with the largest sum of coverage fractions.
max Maximum value of cells that intersect the polygon, ignoring coverage fractions.
mean Mean value of cells that intersect the polygon, weighted by the fraction of the cell that is covered.
median Median value of cells that intersect the polygon, weighted by the fraction of the cell that is covered.
quantile Arbitrary quantile value of cells that intersect the polygon, weighted by the fraction of the cell that is covered.
min Minimum value of cells that intersect the polygon, ignoring coverage fractions.
minority The raster value with the smallest sum of coverage fractions.
sum Sum of values of raster cells that intersect the polygon, with each raster value weighted by its coverage fraction.
variety The number of distinct raster values in cells wholly or partially covered by the polygon.
variance The population variance of cell values, weighted by the fraction of each cell that is covered by the polygon.
stdev The population standard deviation of cell values, weighted by the fraction of each cell that is covered by the polygon.
coefficient_of_variation The population coefficient of variation of cell values, weighted by the fraction of each cell that is covered by the polygon.
frac Fraction of covered cells that are occupied by each distinct raster value.

Three additional summary operations require the use of a second weighting raster, provided in the weights argument to exact_extract:

Name Description
weighted_mean Mean value of defined (non-NA) cells that intersect the polygon, weighted by the product of the coverage fraction and the value of a second weighting raster.
weighted_sum Sum of defined (non-NA) values of raster cells that intersect the polygon, multiplied by the coverage fraction and the value of a second weighting raster.
weighted_variance Population variance of defined (non-NA) values of cells that intersect the polygon, weighted by the product of the coverage fraction and the value of a second weighting raster.
weighted_stdev Population standard deviation of defined (non-NA) values of raster cells that intersect the polygon, multiplied by the coverage fraction and the value of a second weighting raster.
weighted_frac Fraction of covered cells that are occupied by each distinct raster value, with coverage fractions multiplied by the value of a second weighting raster.

Weighted usage is discussed in more detail below.

Undefined (NA) values are ignored in all of the named summary operations when they occur in the value raster. When they occur in the weighting raster, they cause the result of the summary operation to be NA.

Summary Functions

In addition to the summary operations described above, exact_extract can accept an R function to summarize the cells covered by the polygon. Because exact_extract takes into account the fraction of the cell that is covered by the polygon, the summary function must take two arguments: the value of the raster in each cell touched by the polygon, and the fraction of that cell area that is covered by the polygon. (This differs from raster::extract, where the summary function takes the vector of raster values as a single argument and effectively assumes that the coverage fraction is 1.0.)

An example of a built-in function with the appropriate signature is weighted.mean. Some examples of custom summary functions are:

# Number of cells covered by the polygon (raster values are ignored)
exact_extract(rast, poly, function(values, coverage_fraction)
                            sum(coverage_fraction))

# Sum of defined raster values within the polygon, accounting for coverage fraction
exact_extract(rast, poly, function(values, coverage_fraction)
                            sum(values * coverage_fraction, na.rm=TRUE))

# Number of distinct raster values within the polygon (coverage fractions are ignored)
exact_extract(rast, poly, function(values, coverage_fraction)
                            length(unique(values)))

# Number of distinct raster values in cells more than 10% covered by the polygon
exact_extract(rast, poly, function(values, coverage_fraction)
                            length(unique(values[coverage_fraction > 0.1])))

Weighted Usage

exact_extract allows for calculation of summary statistics based on multiple raster layers, such as a population-weighted temperature. 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.)

One application of this feature is the calculation of zonal statistics on raster data in geographic coordinates. The previous calculation of mean precipitation amount across Brazilian municipalities assumed that each raster cell covered the same area, which is not correct for rasters in geographic coordinates (latitude/longitude).

We can correct for varying cell areas by creating a weighting raster with the area of each cell in the primary raster using the area function from the raster package.

Weighted Summary Operations

Performing a weighted summary with the weighted_mean and weighted_sum operations is as simple as providing a weighting RasterLayer or RasterStack to the weights argument of exact_extract.

The area-weighted mean precipitation calculation can be expressed as:

brazil$mean_dec_prec_weighted <- exact_extract(prec[[12]], brazil, 'weighted_mean', weights = area(prec))

With the relatively small polygons used in this example, the error introduced by assuming constant cell area is negligible. However, for large polygons that span a wide range of latitudes, this may not be the case.

Weighted Summary Functions

A weighting raster can also be provided when an R summary function is used. When a weighting raster is provided, the summary function must accept a third argument containing the values of the weighting raster.

An equivalent to the weighted_mean usage above could be written as:

brazil$mean_dec_prec_weighted <- 
  exact_extract(prec[[12]], brazil, function(values, coverage_frac, weights) {
    weighted.mean(values, coverage_frac * weights)
  }, weights = area(prec))

Or, to calculate the area-weighted mean precipitation for all months:

brazil <- cbind(brazil,
  exact_extract(prec, brazil, function(values, coverage_frac, weights) {
    weighted.mean(values, coverage_frac * weights)
  },
  weights = area(prec),
  stack_apply = TRUE))

In this example, the stack_apply argument is set to TRUE so that the summary function will be applied to each layer of prec independently. (If stack_apply = FALSE, the summary function will be called with all values of prec in a 12-column data frame.)

Additional Usages

Multi-Raster Summary Functions

A multi-raster summary function can also be written to implement complex behavior that requires that multiple layers in a RasterStack be considered simultaneously.

Here, we compute an area-weighted average temperature by calling exact_extract with a RasterStack of minimum and maximum temperatures, and a RasterLayer, of cell areas.

tmin <- getData('worldclim', var = 'tmin', res = 10)
tmax <- getData('worldclim', var = 'tmax', res = 10)

temp <- stack(tmin[[12]], tmax[[12]])

brazil$tavg_dec <- exact_extract(temp, brazil,
  function(values, coverage_fraction, weights) {
    tavg <- 0.5*(values$tmin12 + values$tmax12)
    weighted.mean(tavg, coverage_fraction * weights)
  }, weights = area(prec))

When exact_extract is called with a RasterStack of values or weights and stack_apply = FALSE (the default), the values or weights from each layer of the RasterStack will be provided to the summary function as a data frame.

In the example above, the summary function is provided with a data frame of values (containing the values for each layer in the temp stack), a vector of coverage fractions, and a vector of weights.

Multi-Valued Summary Functions

In some cases, it is desirable for a summary function to return multiple values for each input feature. A common application is to summarize the fraction of each polygon that is covered by a given class of a categorical raster. This can be accomplished by writing a summary function that returns a one-row data frame for each input feature. The data frames for each feature will be combined into a single data frame using using rbind or, if it is available, dplyr::bind_rows.

In this example, the mean temperature for each municipality is returned for each altitude category.

altitude <- getData('alt', country = 'BRA')

prec_for_altitude <- exact_extract(prec[[12]], brazil, function(prec, frac, alt) {
  # ignore cells with unknown altitude
  prec <- prec[!is.na(alt)]
  frac <- frac[!is.na(alt)]
  alt <- alt[!is.na(alt)]
  
  low <- !is.na(alt) & alt < 500
  high <- !is.na(alt) & alt >= 500

  data.frame(
    prec_low_alt = weighted.mean(prec[low], frac[low]),
    prec_high_alt = weighted.mean(prec[high], frac[high])
  )
}, weights = altitude)

Rasterization

exactextractr can rasterize polygons though computation of the coverage fraction in each cell. The coverage_fraction function returns a RasterLayer with values from 0 to 1 indicating the fraction of each cell that is covered by the polygon. Because this function generates a RasterLayer for each feature in the input dataset, it can quickly consume a large amount of memory. Depending on the analysis being performed, it may be advisable to manually loop over the features in the input dataset and combine the generated rasters during each iteration.

Performance

For typical applications, exactextractr is much faster than the raster package and somewhat faster than the terra package. An example benchmark is below:

brazil <- st_as_sf(getData('GADM', country='BRA', level=1))
brazil_spat <- as(brazil, 'SpatVector')

prec_rast <- getData('worldclim', var='prec', res=10)
prec_terra <- rast(prec_rast) 
prec12_rast <- prec_rast[[12]]
prec12_terra <- rast(prec_rast[[12]])

microbenchmark(
  extract(prec_rast, brazil, mean, na.rm = TRUE),
  extract(prec_terra, brazil_spat, mean, na.rm = TRUE),
  exact_extract(prec_rast, brazil, 'mean', progress = FALSE),
  exact_extract(prec_terra, brazil, 'mean', progress = FALSE),
  extract(prec12_rast, brazil, mean, na.rm = TRUE),
  extract(prec12_terra, brazil_spat, mean, na.rm = TRUE),
  exact_extract(prec12_rast, brazil, 'mean', progress = FALSE),
  exact_extract(prec12_terra, brazil, 'mean', progress = FALSE),
  times = 5)
Package Raster Type Layers Expression Time (ms)
raster RasterLayer 1 extract(prec_rast, brazil, mean, na.rm = TRUE) 48708
terra SpatRaster 1 extract(prec_terra, brazil_spat, mean, na.rm = TRUE) 436
exactextractr RasterLayer 1 exact_extract(prec_rast, brazil, "mean", progress = FALSE) 1541
exactextractr SpatRaster 1 exact_extract(prec_terra, brazil, "mean", progress = FALSE) 129
raster RasterStack 12 extract(prec12_rast, brazil, mean, na.rm = TRUE) 10148
terra SpatRaster 12 extract(prec12_terra, brazil_spat, mean, na.rm = TRUE) 266
exactextractr RasterLayer 12 exact_extract(prec12_rast, brazil, "mean", progress = FALSE) 222
exactextractr SpatRaster 12 exact_extract(prec12_terra, brazil, "mean", progress = FALSE) 112

Actual performance is a complex topic that can vary dramatically depending on factors such as:

  • the number of layers in the input raster(s)
  • the data type of input rasters (for best performance, use a terra::SpatRaster)
  • the raster file format (GeoTIFF, netCDF, etc)
  • the chunking strategy used by the raster file (striped, tiled, etc.)
  • the relative size of the area to be read and the GDAL block cache

If exact_extract is called with progress = TRUE, messages will be emitted if the package detects a situation that could lead to poor performance, such as a raster chunk size that is too large to allow caching of blocks between vector features.

If performance is poor, it may be possible to improve performance by:

  • increasing the max_cells_in_memory parameter
  • increasing the size of the GDAL block cache
  • rewriting the input rasters to use a different chunking scheme
  • processing inputs as batches of nearby polygons

Accuracy

Results from exactextractr are more accurate than other common implementations because raster pixels that are partially covered by polygons are considered. The significance of partial coverage increases for polygons that are small or irregularly shaped. For the 5500 Brazilian municipalities used in the example, the error introduced by incorrectly handling partial coverage is less than 1% for 88% of municipalities and reaches a maximum of 9%.

Dependencies

Installation requires version 3.5 or greater of the GEOS geometry processing library. It is recommended to use the most recent released version for best performance. On Windows, GEOS will be downloaded automatically as part of package install. On MacOS, it can be installed using Homebrew (brew install geos). On Linux, it can be installed from system package repositories (apt-get install libgeos-dev on Debian/Ubuntu, or yum install libgeos-devel on CentOS/RedHat.)

exactextractr's People

Contributors

dbaston avatar mdsumner avatar rekyt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

exactextractr's Issues

Memory error with coverage_fraction

Hi there,
I am getting the following:
Error in CPP_coverage_fraction(x, wkb, crop) :
Evaluation error: cannot allocate vector of size 13.6 Mb.
Any way of calculating this in chunks to avoid memory issues?
Thanks, Herry

Github version failing to compile on Win 10

Hi,

this is just to let you know that trying to install the github version on Windows 10, I get the following error:

c:/Rtools/mingw_32/bin/g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-3.6.3/include" -DNDEBUG  -I"D:/Documents/R/win-library/3.6/Rcpp/include"     -std=c++14 -I../windows/gdal2-2.2.3/include/geos   -O2 -Wall  -mtune=core2 -c RcppExports.cpp -o RcppExports.o
c:/Rtools/mingw_32/bin/g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-3.6.3/include" -DNDEBUG  -I"D:/Documents/R/win-library/3.6/Rcpp/include"     -std=c++14 -I../windows/gdal2-2.2.3/include/geos   -O2 -Wall  -mtune=core2 -c exact_extract.cpp -o exact_extract.o
In file included from exactextract/src/raster_stats.h:23:0,
                 from exact_extract.cpp:25:
exactextract/src/variance.h: In member function 'constexpr void exactextract::WestVariance::process(double, double) const':
exactextract/src/variance.h:42:15: error: assignment of member 'exactextract::WestVariance::sum_w' in read-only object
         sum_w += w;
               ^
exactextract/src/variance.h:43:14: error: assignment of member 'exactextract::WestVariance::mean' in read-only object
         mean += (w / sum_w) * (x - mean_old);
              ^
exactextract/src/variance.h:44:11: error: assignment of member 'exactextract::WestVariance::t' in read-only object
         t += w * (x - mean_old) * (x - mean);
           ^
exactextract/src/variance.h:39:20: error: invalid return type 'void' of constexpr function 'constexpr void exactextract::WestVariance::process(double, double) const'
     constexpr void process(double x, double w) {
                    ^
make: *** [C:/PROGRA~1/R/R-3.6.3/etc/i386/Makeconf:215: exact_extract.o] Error 1
ERROR: compilation failed for package 'exactextractr'

Predefined 'sum' function returning 0 instead of NA with raster extended internally by the package

Hi again,
I was testing your fantastic package with my data and I found something weird using it with polygons whose extent is greater than the raster one.

Here the data for the reproducible example

Prologue
I tried this:
species$sum <- exact_extract(r.example, species, 'sum')
where r.example is the raster and species is the shapefile, and I got 0 as results both for Species 1 and Species 3.

Basically, "Species 1" polygon lies outside the raster range. I suppose that in cases like this, the package extends the raster before any other summary operation. On the other hand, "Species 3" lies within the raster range but only overlaps raster cells with NA.

Since I expected to get NA for Species 1 and 3 (and not 0), I started to investigate and I found this . That is, when R sum function is applied to only NA values, with na.rm = T, it returns 0 (and not NA as one could expect).
In R language:
sum(NA, NA, na.rm = T) returns 0

To solve the issue, the solution proposed is to use na.rm = any(!is.na(x))).

Here starts the issue with the exactextract package.

In order to apply the aforementioned solution with the sum operation, I used the package with the following customised function:

species$sum <- exact_extract(r.example, species, function(values, coverage_frac) sum(values, na.rm = any(!is.na(values))))

The command worked properly returning NA for Species 3 , but not for Species 1 (it returned 0).
The only reason I could imagine was some kind of problem with the raster expansion internal to the package functioning (since Species 1 lies outside the raster). To test my hypothesis I previously expanded the raster, introducing NA for the new cells:

e <- extent(-180, 180, -90, 90)
r.ext <- extend(r.example, e, value = NA)

Then I re-used the customised function with the new manually-extended raster:

species$sum <- exact_extract(r.ext , species, function(values, coverage_frac) sum(values, na.rm = any(!is.na(values))))

This worked properly, returning NA both for Species 1 and 3.
Maybe, when extending the raster 0 values are introduced instead of NAs? This could explain such behaviour.

I didn't test the issue with the other functions.

Thanks for your work!

inconsistent behavior in exact_extract()

I was exploring the function exact_extract() and its arguments, when I noticed a strange behavior by switching on the argument include_cell:

library(raster)
library(sf)
library(exactextractr)

set.seed(1)

# sample raster
r <- raster(xmn=0, xmx=10, ymn=0, ymx=10, ncols=10, nrows=10, vals = sample(1:3, size = 10*10, replace = T))

# sample feature collection
g <- st_make_grid(
        x = st_as_sfc(st_bbox(r)),
        cellsize = 2,
        what = "polygons",
        square = T
     )

# proportion of cells with 1's inside each feature with include_cell = F
res1 = exact_extract(r, g, include_cell = F, fun = function(value, fraction) {
  sum(fraction[value == 1]) / sum(fraction) }
)

# proportion of cell with 1's inside each feature with include_cell = T
res2 = exact_extract(r, g, include_cell = T, fun = function(value, fraction) {
  sum(fraction[value == 1]) / sum(fraction) }
)

# res1 & res2 should be equal, and indeed they are expcet for the weird NA in row 21
cbind(res1, res2)
> cbind(res1, res2)
      res1 res2
 [1,] 0.50 0.50
 [2,] 0.25 0.25
 [3,] 0.25 0.25
 [4,] 0.25 0.25
 [5,] 0.25 0.25
 [6,] 0.75 0.75
 [7,] 0.25 0.25
 [8,] 0.00 0.00
 [9,] 0.50 0.50
[10,] 0.50 0.50
[11,] 0.25 0.25
[12,] 0.00 0.00
[13,] 0.75 0.75
[14,] 0.00 0.00
[15,] 0.00 0.00
[16,] 0.50 0.50
[17,] 0.75 0.75
[18,] 0.25 0.25
[19,] 0.50 0.50
[20,] 0.00 0.00
[21,] 0.50   NA
[22,] 0.75 0.75
[23,] 0.25 0.25
[24,] 0.00 0.00
[25,] 0.25 0.25

Feature request: Add polygon ID variable to output

Not sure if this is the appropriate place for this, but I'd like to suggest a feature that adds an ID variable to the output dataframe when you're using exact_extract() with a set of polygons over many raster layers. That would really facilitate joins with other data frames.

It's entirely possible I missed this functionality while reading the documentation, so if it already exists please let me know!

row 18446744073709551574 is out of range

When trying to run partial_mask, I'm getting this error for whatever raster and vector data I'm trying to use:
Error in CPP_weights(as.vector(raster::extent(x)), raster::res(x), wkb) : Row 18446744073709551574 is out of range.

I've created this stripped down example the reproduce the problem:

  1. Create an empty raster with a resolution of 100 x 100 meters and fake some values
r <- raster(xmn=391030, xmx=419780, ymn=5520000, ymx=5547400)
res(r) = c(100, 100)
crs(r) <- CRS('+init=EPSG:25832')
values(r) <- 1:ncell(r)
  1. Load polygons (rename the attached polygons.txt to polygons.geojson)
    p <- st_read("polygons.geojson", crs = 25832)

  2. Execute partial_mask
    partial_mask(r, p)

I'm running R version 3.4.3 (2017-11-30) on Windows 7, 64-bit.

citation?

This is a hugely valuable library. Is there a preferred citation for those using in for peer-review papers?

Thanks for the great work!

Mike

Github version failing to compile on Win 8.1

Hello Mr. Baston,

Like the previous message from "lbusett", I did not succeed in compiling exactextractr from github.
After the following command...
devtools::install_github("isciences/exactextractr", lib="C:/Users/toto/Documents/essaiexactextractr")

R returns the following error message (cf below) :

C:/Rtools/mingw_32/bin/g++ -std=gnu++11 -I"C:/PROGRA1/R/R-361.3/include" -DNDEBUG -I"C:/Users/toto/Documents/R/win-library/3.6/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=core2 -c RcppExports.cpp -o RcppExports.o
C:/Rtools/mingw_32/bin/g++ -std=gnu++11 -I"C:/PROGRA1/R/R-361.3/include" -DNDEBUG -I"C:/Users/toto/Documents/R/win-library/3.6/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=core2 -c exact_extract.cpp -o exact_extract.o
In file included from exactextract/src/raster_stats.h:23:0,
from exact_extract.cpp:25:
exactextract/src/variance.h: In member function 'constexpr void exactextract::WestVariance::process(double, double) const':
exactextract/src/variance.h:42:15: error: assignment of member 'exactextract::WestVariance::sum_w' in read-only object
sum_w += w;
^
exactextract/src/variance.h:43:14: error: assignment of member 'exactextract::WestVariance::mean' in read-only object
mean += (w / sum_w) * (x - mean_old);
^
exactextract/src/variance.h:44:11: error: assignment of member 'exactextract::WestVariance::t' in read-only object
t += w * (x - mean_old) * (x - mean);
^
exactextract/src/variance.h:39:20: error: invalid return type 'void' of constexpr function 'constexpr void exactextract::WestVariance::process(double, double) const'
constexpr void process(double x, double w) {
^
make: *** [C:/PROGRA1/R/R-361.3/etc/i386/Makeconf:215: exact_extract.o] Error 1
ERROR: compilation failed for package 'exactextractr'

  • removing 'C:/Users/toto/Documents/essaiexactextractr/exactextractr'
    Erreur : Failed to install 'exactextractr' from GitHub:
    (converti depuis l'avis) installation of package ‘C:/Users/toto/AppData/Local/Temp/RtmpC8rHUT/file14206e5e77af/exactextractr_0.4.0.tar.gz’ had non-zero exit status

Thank you forward
Loïc

NetCDF time stab

I'm loading a NetCDF file containing temperatures for a 12 month period (1 per month) with:

my_brick = brick("my_file.nc", var="temperature")

And have a shapefile my_shape.

I'd like to get the average value of temperature across space and time for each region in the shapefile.

Using

out = exact_extract(my_brick, my_shape, stack_apply=FALSE, fun=function(values, coverage){
   length(values)
})

gives 12 - so presumably one value for each month in the time period... but that seems to imply a spatial reduction.

Using

out = exact_extract(my_brick, my_shape, stack_apply=TRUE, fun=function(values, coverage){
   length(values)
})

gives numbers of values which are not divisible by 12, so it feels like something has gone wrong since if it was just handing me a data frame of all the spatial values for each month then the number of values should be evenly divisible by 12.

Could you clarify how to get this spatial+temporal average?

Inability to deal with null (NA) values.

Hi,
everything works great (incredibly fast!). However, when a polygon zone encloses a few NA values the result of the function returns NA. Could not find a way to bypass this on the function code.
Cheers,
César

exactextractr weighted summation command

I am curious about documentation for the exactextractr package. I have installed it, but am unclear on what commands are available within it. Specifically, I would like to produce a weighted sum of raster values within a polygon grid where some rasters are only partially covered by the polygons. Is this possible with exact_extract?

Thank you

Not working for large files

I tried the library for the first time.
Zonal stat on Brazil raster file (resolution 100meters) with 310896 polygons.

Error in CPP_stats(x, wkb, fun) :
Evaluation error: long vectors not supported yet: memory.c:3486.

Long extract time for multiband raster

There's probably something basic that I'm doing wrong here, but I have two raster stacks that are derived from the same primary source (same resolution, extent and number of layers). With a vector layer of ~40k features, one stack takes minutes and the other stack took about 18 hours.
The only difference that I can see is that the one that took way longer has two bands.

I imported that one like so:
st_laiSNAP <- stack(list.files(path = 'LAI_S2_SNAP/', pattern = "\\.tif$", full.names = T), bands = 1)

The output of str on the problem stack is below

The differences I see are:

  • @ blockrows/cols : int 10980 (the quicker stack is int 256)
  • @ nbands : int 2 (the quicker stack has 1)

The exactextractr output of the problem stack is just as expected. No problems there.

With the same resolution, extent, n layers and features, why is there such a big difference in processing time?

Exactextractr version: 0.2.1

Problem stack:
Formal class 'RasterStack' [package "raster"] with 11 slots
..@ filename: chr ""
..@ layers :List of 6
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A006069_20180505T112304_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi TRUE
.. .. .. .. .. ..@ min : num -0.672
.. .. .. .. .. ..@ max : num 13.9
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006069_20180505T112304_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A006355_20180525T112111_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006355_20180525T112111_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A006398_20180528T113438_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006398_20180528T113438_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A006541_20180607T113457_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006541_20180607T113457_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A006927_20180704T112112_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006927_20180704T112112_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "\L1C_T30UWG_A015764_20180629T112537_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A015764_20180629T112537_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
..@ title : chr(0)
..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. ..@ xmin: num 5e+05
.. .. ..@ xmax: num 609780
.. .. ..@ ymin: num 6090240
.. .. ..@ ymax: num 6200040
..@ rotated : logi FALSE
..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. ..@ geotrans: num(0)
.. .. ..@ transfun:function ()
..@ ncols : int 10980
..@ nrows : int 10980
..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
..@ history : list()
..@ z : list()

Problem stack
Formal class 'RasterStack' [package "raster"] with 11 slots
..@ filename: chr ""
..@ layers :List of 6
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A006069_20180505T112304_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi TRUE
.. .. .. .. .. ..@ min : num -0.672
.. .. .. .. .. ..@ max : num 13.9
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006069_20180505T112304_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A006355_20180525T112111_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006355_20180525T112111_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A006398_20180528T113438_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006398_20180528T113438_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A006541_20180607T113457_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006541_20180607T113457_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A006927_20180704T112112_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A006927_20180704T112112_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
.. ..$ :Formal class 'RasterLayer' [package "raster"] with 12 slots
.. .. .. ..@ file :Formal class '.RasterFile' [package "raster"] with 13 slots
.. .. .. .. .. ..@ name : chr "C:\Users\Simon\Documents\GAAFS\Ideas\EOcropModel\LAI_S2_SNAP\L1C_T30UWG_A015764_20180629T112537_10m_lai.tif"
.. .. .. .. .. ..@ datanotation: chr "FLT4S"
.. .. .. .. .. ..@ byteorder : chr "little"
.. .. .. .. .. ..@ nodatavalue : num -Inf
.. .. .. .. .. ..@ NAchanged : logi FALSE
.. .. .. .. .. ..@ nbands : int 2
.. .. .. .. .. ..@ bandorder : chr "BIL"
.. .. .. .. .. ..@ offset : int 0
.. .. .. .. .. ..@ toptobottom : logi TRUE
.. .. .. .. .. ..@ blockrows : int 10980
.. .. .. .. .. ..@ blockcols : int 10980
.. .. .. .. .. ..@ driver : chr "gdal"
.. .. .. .. .. ..@ open : logi FALSE
.. .. .. ..@ data :Formal class '.SingleLayerData' [package "raster"] with 13 slots
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ offset : num 0
.. .. .. .. .. ..@ gain : num 1
.. .. .. .. .. ..@ inmemory : logi FALSE
.. .. .. .. .. ..@ fromdisk : logi TRUE
.. .. .. .. .. ..@ isfactor : logi FALSE
.. .. .. .. .. ..@ attributes: list()
.. .. .. .. .. ..@ haveminmax: logi FALSE
.. .. .. .. .. ..@ min : num Inf
.. .. .. .. .. ..@ max : num -Inf
.. .. .. .. .. ..@ band : int 1
.. .. .. .. .. ..@ unit : chr ""
.. .. .. .. .. ..@ names : chr "L1C_T30UWG_A015764_20180629T112537_10m_lai"
.. .. .. ..@ legend :Formal class '.RasterLegend' [package "raster"] with 5 slots
.. .. .. .. .. ..@ type : chr(0)
.. .. .. .. .. ..@ values : logi(0)
.. .. .. .. .. ..@ color : logi(0)
.. .. .. .. .. ..@ names : logi(0)
.. .. .. .. .. ..@ colortable: logi(0)
.. .. .. ..@ title : chr(0)
.. .. .. ..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. .. .. .. ..@ xmin: num 5e+05
.. .. .. .. .. ..@ xmax: num 609780
.. .. .. .. .. ..@ ymin: num 6090240
.. .. .. .. .. ..@ ymax: num 6200040
.. .. .. ..@ rotated : logi FALSE
.. .. .. ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. .. .. .. ..@ geotrans: num(0)
.. .. .. .. .. ..@ transfun:function ()
.. .. .. ..@ ncols : int 10980
.. .. .. ..@ nrows : int 10980
.. .. .. ..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. .. .. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
.. .. .. ..@ history : list()
.. .. .. ..@ z : list()
..@ title : chr(0)
..@ extent :Formal class 'Extent' [package "raster"] with 4 slots
.. .. ..@ xmin: num 5e+05
.. .. ..@ xmax: num 609780
.. .. ..@ ymin: num 6090240
.. .. ..@ ymax: num 6200040
..@ rotated : logi FALSE
..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
.. .. ..@ geotrans: num(0)
.. .. ..@ transfun:function ()
..@ ncols : int 10980
..@ nrows : int 10980
..@ crs :Formal class 'CRS' [package "sp"] with 1 slot
.. .. ..@ projargs: chr "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
..@ history : list()
..@ z : list()

Potentially make exact_extract faster?

Dear dbaston,

Thanks for this wonderful package. For my research, I have been exploring the fastest way to extract raster values for polygons. While I was experimenting with velox and exactextractr packages, I found that exactextractr's extraction speed suffers considerably as the number of polygons increases (with the spatial extent of the polygons and raster resolutions held fixed) while velox does not. On the other hand, velox suffers when the number of raster cells increase while exactextratr does not.

The code below demonstrates the first point. The raster data holds 1,630,950 cells. The number of polygons to which the raster values are extracted are varied: 1) 79, 2) 1622, and 3) 6187 polygons.

  • The velox approach finishes the extraction job in less than a second.
  • The exactextractr approach takes 1.12, 6.706, and 23.655 seconds, respectively.

The amount of data to move around are very similar across different number of polygons as the resolution and spatial extent of the raster data stay the same across the experiments and because the polygons are not overlapping. I am guessing many many calls of getValuesBlock() (and other functions to process by chunk) is hurting the performance of exactextractr. If so, is there any way you can modify the way you process the data by chunk in a way that reduces the number of chunks to avoid this problem? I do not completley understand how exact_extract() works, but just wanted to ask if it is possible because that would make the function even better (I think).

library(velox)
library(raster)
library(sf)
library(exactextractr)

#===================================
# Prepare datasets
#===================================
#--- US state boundaries ---#
US_state <- st_as_sf(map(database = "state", plot = FALSE, fill = TRUE)) 

#--- raster data ---#
raster_US <- st_rasterize(US_state) %>% 
  as("Raster") %>% 
  disaggregate(fact = 5)  

#--- create a brick ---#
raster_US_brick <- brick(raster_US, raster_US, raster_US, raster_US, raster_US)

#--- create polygons for which we extract data from the brick ---#
polys_100 <- st_make_grid(US_state, n = c(10, 10))
polys_2500 <- st_make_grid(US_state, n = c(50, 50))
polys_10000 <- st_make_grid(US_state, n = c(100, 100))

#===================================
# Comparison: changing the number of polygons 
#===================================
#--------------------------
# polys_100 (79 polygons)
#--------------------------
length(polys_100)

#--- exact_extract ---#
tic()
a <- exact_extract(raster_US_brick, polys_100)
toc()

object.size(a) %>% format(units = "Mb")

#--- velox ---#
tic()
a <- velox(raster_US_brick)$extract(polys_100)
toc()

#--------------------------
# polys_2500 (1622 polygons)
#--------------------------
length(polys_2500)

#--- exact_extract ---#
tic()
a <- exact_extract(raster_US_brick, polys_2500, FUN = mean)
toc()

object.size(a) %>% format(units = "Mb")

#--- velox ---#
tic()
a <- velox(raster_US_brick)$extract(polys_2500)
toc()

#--------------------------
# polys_10000 (6187 polygons)
#--------------------------
length(polys_10000)

#--- exact_extract ---#
tic()
a <- exact_extract(raster_US_brick, polys_10000)
toc()

object.size(a) %>% format(units = "Mb")

#--- velox ---#
tic()
a <- velox(raster_US_brick)$extract(polys_10000)
toc()

Error in weighted.mean

When using weighted.mean as the summary function with multiple raster layers in:
exact_extract(ras, shp, fun = weighted.mean)

where:

  • ras is a "RasterStack" object with nlayers(x) > 1, and

  • shp is an "sf" object (i.e. class(sf::st_geometry(y)) == "sfc_POLYGON") with nrow(y) > 1

I receive the error:

Error in weighted.mean.default(vals, cov_fracs, ...) :
'x' and 'w' must have the same length

Looking into the methods for getMethod("exact_extract" , signature = c( x = "Raster" , y = "sfc_POLYGON")) shows that the error is occurring because weighted.mean(x = vals, w = cov_fracs) requires that input w have the same "length" as x. Thus, when object vals is created in the function through raster::getValuesBlock() for a "RasterStack", weighted.mean fails because it can't handle multiple columns. This can be fixed on the users end by defining a custom version of weighted.mean() using apply():

apply.weighted.mean <- function(x, y){apply(X = x, MARGIN = 2, FUN = weighted.mean, w = y)}

v <- exact_extract(x = ras, y = shp, fun = apply.weighted.mean)

Missleading progress bar

The progress bar gives directly 100%. It definitly lifts up the mood but a bit missleading ;)
Either changing implementation or removing it?
But otherwise great package!

No C++14 compiler identified by R CMD config CXX14

I'm trying to install exactextractr in ubuntu 18.04 with Microsoft R but I get this error. Can anyone help me? Thanks

> install.packages("~/R/exactextractr_0.5.1.tar.gz", repos = NULL, type = "source")
Installing package into ‘/home/cappannonno/R/x86_64-pc-linux-gnu-library/4.0’
(as ‘lib’ is unspecified)
Microsoft R Open 4.0.2
The enhanced R distribution from Microsoft
Microsoft packages Copyright (C) 2020 Microsoft Corporation

Using the Intel MKL for parallel mathematical computing (using 2 cores).

Default CRAN mirror snapshot taken on 2020-07-16.
See: https://mran.microsoft.com/.

* installing *source* package ‘exactextractr’ ...
** package ‘exactextractr’ successfully unpacked and MD5 sums checked
** using staged installation
configure: exactextractr: 0.5.1
configure: error: "No C++14 compiler identified by R CMD config CXX14"
ERROR: configuration failed for package ‘exactextractr’
* removing ‘/home/cappannonno/R/x86_64-pc-linux-gnu-library/4.0/exactextractr’
Warning in install.packages :
  installation of package ‘/home/cappannonno/R/exactextractr_0.5.1.tar.gz’ had non-zero exit status

exact_extractr very different behaviour to raster::extract in center of polygon

Hi,
Thanks for a awesome and fast package. I have been using exact_extract quite a bit but have run into a problem.

I was trying to extract raster values into a polygon that sits well within the bounds of the raster, but values are only being extracted onto the border of the polygon.

When I compared to the results of raster::extract there was no problems.
I haven't managed to be able to make a small reproducible example as this problem only showed up now and I have been using exact_extract for a while now.

Any help would be much appreciated!

extract(r, p)[[1]] %>% length() #823
exact_extract(r, p)[[1]] %>% nrow() #160

Data (Sorry for the dput dump):

p <- 
structure(list(rowname = "3", Zone = structure(3L, .Label = c("zone_1", 
"zone_2", "zone_3"), class = "factor"), geometry = structure(list(
    `31` = structure(list(structure(c(146.375, 146.425, 146.475, 
    146.475, 146.525, 146.575, 146.575, 146.625, 146.675, 146.725, 
    146.775, 146.775, 146.825, 146.875, 146.925, 146.975, 147.025, 
    147.075, 147.125, 147.125, 147.175, 147.225, 147.225, 147.275, 
    147.325, 147.374999999999, 147.374999999999, 147.374999999999, 
    147.374999999999, 147.374999999999, 147.374999999999, 147.374999999999, 
    147.374999999999, 147.374999999999, 147.374999999999, 147.374999999999, 
    147.374999999999, 147.374999999999, 147.374999999999, 147.325, 
    147.275, 147.275, 147.225, 147.225, 147.225, 147.175, 147.175, 
    147.225, 147.225, 147.175, 147.175, 147.125, 147.075, 147.075, 
    147.125, 147.125, 147.125, 147.125, 147.175, 147.175, 147.175, 
    147.175, 147.225, 147.225, 147.225, 147.175, 147.175, 147.225, 
    147.225, 147.275, 147.275, 147.325, 147.374999999999, 147.374999999999, 
    147.374999999999, 147.374999999999, 147.374999999999, 147.374999999999, 
    147.325, 147.325, 147.275, 147.275, 147.275, 147.275, 147.275, 
    147.225, 147.225, 147.175, 147.125, 147.125, 147.125, 147.075, 
    147.025, 147.025, 146.975, 146.925, 146.925, 146.875, 146.825, 
    146.775, 146.775, 146.725, 146.725, 146.675, 146.675, 146.625, 
    146.625, 146.575, 146.525, 146.525, 146.525, 146.475, 146.475, 
    146.425, 146.375, 146.325, 146.275, 146.225, 146.175, 146.125, 
    146.075, 146.025, 146.025, 146.025, 146.025, 145.975, 145.925, 
    145.925, 145.925, 145.975, 145.975, 145.975, 145.975, 146.025, 
    146.025, 146.025, 146.025, 146.025, 146.075, 146.125, 146.125, 
    146.125, 146.175, 146.175, 146.175, 146.175, 146.225, 146.225, 
    146.275, 146.275, 146.275, 146.325, 146.325, 146.325, 146.375, 
    146.375, 146.425, 146.425, 146.425, 146.375, 146.375, 146.425, 
    146.425, 146.425, 146.425, 146.475, 146.475, 146.475, 146.425, 
    146.375, 146.375, 146.375, 146.325, 146.275, 146.275, 146.225, 
    146.225, 146.175, 146.175, 146.125, 146.125, 146.175, 146.175, 
    146.175, 146.225, 146.275, 146.325, 146.375, 146.375, -33.475, 
    -33.475, -33.475, -33.525, -33.525, -33.525, -33.575, -33.575, 
    -33.575, -33.575, -33.575, -33.525, -33.525, -33.525, -33.525, 
    -33.525, -33.525, -33.525, -33.525, -33.575, -33.575, -33.575, 
    -33.525, -33.525, -33.525, -33.525, -33.575, -33.625, -33.675, 
    -33.725, -33.775, -33.825, -33.875, -33.925, -33.975, -34.025, 
    -34.075, -34.125, -34.175, -34.175, -34.175, -34.125, -34.125, 
    -34.175, -34.225, -34.225, -34.275, -34.275, -34.325, -34.325, 
    -34.375, -34.375, -34.375, -34.425, -34.425, -34.475, -34.525, 
    -34.575, -34.575, -34.625, -34.675, -34.725, -34.725, -34.775, 
    -34.825, -34.825, -34.875, -34.875, -34.925, -34.925, -34.975, 
    -34.975, -34.975, -35.025, -35.075, -35.125, -35.175, -35.225, 
    -35.225, -35.175, -35.175, -35.225, -35.275, -35.325, -35.375, 
    -35.375, -35.325, -35.325, -35.325, -35.375, -35.425, -35.425, 
    -35.425, -35.475, -35.475, -35.475, -35.425, -35.425, -35.425, 
    -35.425, -35.475, -35.475, -35.525, -35.525, -35.475, -35.475, 
    -35.425, -35.425, -35.425, -35.475, -35.525, -35.525, -35.475, 
    -35.475, -35.475, -35.475, -35.475, -35.475, -35.475, -35.475, 
    -35.475, -35.475, -35.425, -35.375, -35.325, -35.325, -35.325, 
    -35.275, -35.225, -35.225, -35.175, -35.125, -35.075, -35.075, 
    -35.025, -34.975, -34.925, -34.875, -34.875, -34.875, -34.825, 
    -34.775, -34.775, -34.725, -34.675, -34.625, -34.625, -34.575, 
    -34.575, -34.525, -34.475, -34.475, -34.425, -34.375, -34.375, 
    -34.325, -34.325, -34.275, -34.225, -34.225, -34.175, -34.175, 
    -34.125, -34.075, -34.025, -34.025, -33.975, -33.925, -33.925, 
    -33.925, -33.875, -33.825, -33.825, -33.825, -33.775, -33.775, 
    -33.725, -33.725, -33.675, -33.675, -33.625, -33.625, -33.575, 
    -33.525, -33.525, -33.525, -33.525, -33.525, -33.475), .Dim = c(189L, 
    2L)), structure(c(147.175, 147.175, 147.125, 147.125, 147.175, 
    -35.225, -35.175, -35.175, -35.225, -35.225), .Dim = c(5L, 
    2L))), class = c("XY", "POLYGON", "sfg"))), class = c("sfc_POLYGON", 
"sfc"), precision = 0, bbox = structure(c(xmin = 145.925, ymin = -35.525, 
xmax = 147.374999999999, ymax = -33.475), class = "bbox"), crs = structure(list(
    epsg = 4326L, proj4string = "+proj=longlat +datum=WGS84 +no_defs"), class = "crs"), n_empty = 0L)), row.names = 1L, sf_column = "geometry", agr = structure(c(rowname = NA_integer_, 
Zone = NA_integer_), .Label = c("constant", "aggregate", "identity"
), class = "factor"), class = c("sf", "data.frame"))

r <-
new("RasterLayer", file = new(".RasterFile", name = "", datanotation = "FLT4S", 
    byteorder = "little", nodatavalue = -3.4e+38, NAchanged = FALSE, 
    nbands = 1L, bandorder = "BIL", offset = 0L, toptobottom = TRUE, 
    blockrows = 0L, blockcols = 0L, driver = "", open = FALSE), 
    data = new(".SingleLayerData", values = c(NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, 0.266666666666667, 0.266666666666667, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, NA, 0.366666666666667, 0.4, 0.366666666666667, 
    0.366666666666667, 0.366666666666667, 0.333333333333333, 
    0.3, 0.3, NA, NA, NA, NA, 0.666666666666667, 0.633333333333333, 
    0.7, 0.733333333333333, 0.7, 0.766666666666667, 0.8, NA, 
    NA, 1, 1.06666666666667, 1.06666666666667, NA, NA, NA, NA, 
    NA, 0.466666666666667, 0.5, 0.466666666666667, 0.466666666666667, 
    0.4, 0.333333333333333, 0.3, 0.3, 0.3, 0.366666666666667, 
    0.533333333333333, 0.566666666666667, 0.5, 0.5, 0.566666666666667, 
    0.666666666666667, 0.733333333333333, 0.7, 0.733333333333333, 
    0.8, 0.866666666666667, 1.06666666666667, 1.1, 1.1, NA, NA, 
    NA, NA, 0.533333333333333, 0.566666666666667, 0.633333333333333, 
    0.6, 0.566666666666667, 0.466666666666667, 0.366666666666667, 
    0.333333333333333, 0.3, 0.3, 0.433333333333333, 0.5, 0.5, 
    0.5, 0.533333333333333, 0.566666666666667, 0.666666666666667, 
    0.666666666666667, 0.7, 0.733333333333333, 0.766666666666667, 
    0.866666666666667, 1.03333333333333, 1.1, 1.13333333333333, 
    NA, NA, NA, NA, NA, 0.733333333333333, 0.933333333333333, 
    0.833333333333333, 0.566666666666667, 0.566666666666667, 
    0.4, 0.366666666666667, 0.4, 0.466666666666667, 0.433333333333333, 
    0.466666666666667, 0.5, 0.533333333333333, 0.5, 0.666666666666667, 
    0.666666666666667, 0.7, 0.7, 0.766666666666667, 0.766666666666667, 
    0.933333333333333, 1.03333333333333, 1.06666666666667, 1.13333333333333, 
    NA, NA, NA, NA, NA, NA, 0.9, 0.9, 0.666666666666667, 0.433333333333333, 
    0.4, 0.4, 0.4, 0.433333333333333, 0.466666666666667, 0.533333333333333, 
    0.533333333333333, 0.566666666666667, 0.533333333333333, 
    0.6, 0.7, 0.7, 0.8, 0.866666666666667, 0.866666666666667, 
    0.966666666666667, 1, 1, 1.06666666666667, NA, NA, NA, NA, 
    NA, NA, NA, 0.633333333333333, 0.5, 0.4, 0.4, 0.366666666666667, 
    0.366666666666667, 0.466666666666667, 0.466666666666667, 
    0.466666666666667, 0.566666666666667, 0.666666666666667, 
    0.666666666666667, 0.7, 0.666666666666667, 0.7, 0.833333333333333, 
    0.866666666666667, 0.9, 1, 1, 1, 1.06666666666667, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, 0.4, 0.333333333333333, 0.366666666666667, 
    0.466666666666667, 0.5, 0.533333333333333, 0.6, 0.6, 0.7, 
    0.833333333333333, 0.833333333333333, 0.766666666666667, 
    0.733333333333333, 0.833333333333333, 0.9, 0.933333333333333, 
    0.966666666666667, 1, 1.06666666666667, 1.06666666666667, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.366666666666667, 0.333333333333333, 
    0.333333333333333, 0.433333333333333, 0.466666666666667, 
    0.566666666666667, 0.666666666666667, 0.6, 0.666666666666667, 
    0.766666666666667, 0.833333333333333, 0.9, 0.866666666666667, 
    0.866666666666667, 0.9, 0.866666666666667, 0.9, 0.966666666666667, 
    1.06666666666667, 1.1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    NA, NA, 0.3, 0.333333333333333, 0.333333333333333, 0.533333333333333, 
    0.666666666666667, 0.533333333333333, 0.6, 0.566666666666667, 
    0.8, 0.866666666666667, 0.866666666666667, 0.833333333333333, 
    0.9, 0.933333333333333, 0.933333333333333, 1, 1.06666666666667, 
    1.1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.3, 0.333333333333333, 
    0.3, 0.333333333333333, 0.433333333333333, 0.466666666666667, 
    0.5, 0.566666666666667, 0.6, 0.7, 0.766666666666667, 0.833333333333333, 
    0.833333333333333, 0.933333333333333, 0.966666666666667, 
    1, 1.1, 1.2, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.333333333333333, 
    0.3, 0.3, 0.3, 0.3, 0.366666666666667, 0.7, 0.433333333333333, 
    0.5, 0.566666666666667, 0.633333333333333, 0.733333333333333, 
    0.766666666666667, 0.966666666666667, 0.933333333333333, 
    0.966666666666667, 1.1, 1.1, 1.26666666666667, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, NA, 0.366666666666667, 0.333333333333333, 
    0.266666666666667, 0.266666666666667, 0.333333333333333, 
    0.333333333333333, 0.566666666666667, 0.4, 0.5, 0.666666666666667, 
    0.8, 0.766666666666667, 0.933333333333333, 1.03333333333333, 
    0.966666666666667, 1.06666666666667, 1.13333333333333, 1.23333333333333, 
    1.23333333333333, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
    0.366666666666667, 0.333333333333333, 0.333333333333333, 
    0.266666666666667, 0.3, 0.333333333333333, 0.333333333333333, 
    0.366666666666667, 0.466666666666667, 0.766666666666667, 
    0.8, 0.833333333333333, 0.933333333333333, 0.966666666666667, 
    1.06666666666667, 1.2, 1.43333333333333, 1.4, 1.46666666666667, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.4, 0.366666666666667, 
    0.333333333333333, 0.333333333333333, 0.266666666666667, 
    0.3, 0.3, 0.333333333333333, 0.366666666666667, 0.533333333333333, 
    0.633333333333333, 0.933333333333333, 0.833333333333333, 
    0.833333333333333, 0.966666666666667, 1.1, 1.4, 1.46666666666667, 
    1.56666666666667, 1.66666666666667, NA, NA, NA, NA, NA, NA, 
    NA, NA, NA, NA, 0.333333333333333, 0.333333333333333, 0.333333333333333, 
    0.333333333333333, 0.3, 0.3, 0.333333333333333, 0.433333333333333, 
    0.5, 0.866666666666667, 0.666666666666667, 0.766666666666667, 
    0.833333333333333, 1.03333333333333, 1.16666666666667, 1.4, 
    1.6, 1.76666666666667, 2.06666666666667, NA, NA, NA, NA, 
    NA, NA, NA, NA, NA, NA, 0.4, 0.333333333333333, 0.333333333333333, 
    0.333333333333333, 0.366666666666667, 0.3, 0.333333333333333, 
    0.533333333333333, 0.6, 0.566666666666667, 0.733333333333333, 
    0.733333333333333, 0.9, 0.966666666666667, 1.16666666666667, 
    1.33333333333333, 1.56666666666667, 1.9, 2.16666666666667, 
    NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.5, 0.433333333333333, 
    0.433333333333333, 0.4, 0.433333333333333, 0.433333333333333, 
    0.366666666666667, 0.4, 0.533333333333333, 0.566666666666667, 
    0.566666666666667, 0.7, 0.833333333333333, 1.16666666666667, 
    1.13333333333333, 1.23333333333333, 1.46666666666667, 1.83333333333333, 
    2.1, 2.36666666666667, NA, NA, NA, NA, NA, NA, NA, NA, 0.4, 
    0.6, 0.433333333333333, 0.4, 0.433333333333333, 0.466666666666667, 
    0.5, 0.466666666666667, 0.433333333333333, 0.4, 0.466666666666667, 
    0.6, 0.733333333333333, 0.9, 1.06666666666667, 1.4, 1.5, 
    1.76666666666667, 2.1, 2.26666666666667, 2.46666666666667, 
    NA, NA, NA, NA, NA, NA, NA, NA, 0.366666666666667, 0.4, 0.5, 
    0.433333333333333, 0.433333333333333, 0.533333333333333, 
    0.5, 0.5, 0.5, 0.566666666666667, 0.7, 0.666666666666667, 
    0.9, 1.1, 1.16666666666667, 1.33333333333333, 1.6, 1.9, 2.13333333333333, 
    2.36666666666667, 2.66666666666667, NA, NA, NA, NA, NA, NA, 
    NA, 0.433333333333333, 0.366666666666667, 0.366666666666667, 
    0.366666666666667, 0.933333333333333, 0.966666666666667, 
    0.7, 0.733333333333333, 0.5, 0.5, 0.5, 0.666666666666667, 
    0.666666666666667, 0.733333333333333, 0.933333333333333, 
    1.2, 1.26666666666667, 1.73333333333333, 2.03333333333333, 
    2.13333333333333, 2.63333333333333, 2.9, NA, NA, NA, NA, 
    NA, NA, NA, 0.4, 0.4, 0.366666666666667, 0.366666666666667, 
    0.4, 0.466666666666667, 0.533333333333333, 0.533333333333333, 
    0.5, 0.466666666666667, 0.533333333333333, 0.633333333333333, 
    0.7, 0.8, 0.966666666666667, 1.3, 1.33333333333333, 1.73333333333333, 
    1.9, 2.1, 2.66666666666667, 3, NA, NA, NA, NA, NA, NA, 0.466666666666667, 
    0.4, 0.4, 0.4, 0.433333333333333, 0.4, 0.4, 0.6, 0.666666666666667, 
    0.433333333333333, 0.533333333333333, 0.633333333333333, 
    0.633333333333333, 0.633333333333333, 0.766666666666667, 
    0.866666666666667, 1, 1.46666666666667, 1.63333333333333, 
    1.96666666666667, 2.13333333333333, 2.36666666666667, 2.66666666666667, 
    NA, NA, NA, NA, NA, 0.5, 0.5, 0.4, 0.4, 0.4, 0.4, 0.433333333333333, 
    0.4, 0.433333333333333, 0.433333333333333, 0.466666666666667, 
    0.533333333333333, 0.566666666666667, 0.666666666666667, 
    0.666666666666667, 0.8, 0.866666666666667, 1.03333333333333, 
    1.33333333333333, 1.63333333333333, 1.96666666666667, 2, 
    2.3, 2.83333333333333, NA, NA, NA, NA, NA, 0.533333333333333, 
    0.5, 0.4, 0.4, 0.4, 0.433333333333333, 0.433333333333333, 
    0.466666666666667, 0.466666666666667, 0.833333333333333, 
    0.633333333333333, 0.533333333333333, 0.6, 0.633333333333333, 
    0.7, 0.8, 0.9, 1.1, 1.26666666666667, 1.56666666666667, 1.86666666666667, 
    1.96666666666667, 2.4, 2.86666666666667, NA, NA, NA, NA, 
    NA, 0.5, 0.466666666666667, 0.4, 0.4, 0.433333333333333, 
    0.433333333333333, 0.433333333333333, 0.466666666666667, 
    0.866666666666667, 0.533333333333333, 0.466666666666667, 
    0.566666666666667, 0.6, 0.7, 0.733333333333333, 0.833333333333333, 
    0.9, 1.1, 1.23333333333333, 1.5, 1.56666666666667, 1.9, 2.3, 
    2.66666666666667, NA, NA, NA, NA, 0.533333333333333, 0.5, 
    0.433333333333333, 0.4, 0.433333333333333, 0.433333333333333, 
    0.433333333333333, 0.533333333333333, 0.466666666666667, 
    0.466666666666667, 0.5, 0.566666666666667, 0.6, 0.6, 0.633333333333333, 
    0.733333333333333, 0.833333333333333, 0.9, 1.2, 1.2, 1.43333333333333, 
    1.66666666666667, 2.03333333333333, 2.33333333333333, 2.53333333333333, 
    NA, NA, NA, NA, 0.5, 0.466666666666667, 0.433333333333333, 
    0.433333333333333, 0.433333333333333, 0.466666666666667, 
    0.533333333333333, 0.566666666666667, 0.6, 0.566666666666667, 
    0.566666666666667, 0.6, 0.6, 0.6, 0.7, 0.733333333333333, 
    0.833333333333333, 0.933333333333333, 1.2, 1.26666666666667, 
    1.46666666666667, 1.83333333333333, 2.2, 2.36666666666667, 
    2.8, NA, NA, 0.533333333333333, 0.533333333333333, 0.533333333333333, 
    0.466666666666667, 0.466666666666667, 0.433333333333333, 
    0.433333333333333, 0.466666666666667, 0.6, 0.566666666666667, 
    0.6, 0.566666666666667, 0.633333333333333, 0.6, 0.6, 0.633333333333333, 
    0.633333333333333, 0.733333333333333, 0.833333333333333, 
    1.06666666666667, 1.2, 1.43333333333333, 1.46666666666667, 
    1.8, 1.9, 2.2, 2.46666666666667, NA, NA, 0.533333333333333, 
    0.533333333333333, 0.5, 0.5, 0.433333333333333, 0.433333333333333, 
    0.466666666666667, 0.533333333333333, 0.6, 0.666666666666667, 
    0.666666666666667, 0.633333333333333, 0.633333333333333, 
    0.633333333333333, 0.633333333333333, 0.633333333333333, 
    0.7, 0.7, 0.8, 0.9, 1.1, 1.33333333333333, 1.66666666666667, 
    1.56666666666667, 1.83333333333333, 1.93333333333333, 2, 
    NA, NA, 0.5, 0.533333333333333, 0.5, 0.466666666666667, 0.466666666666667, 
    0.466666666666667, 0.533333333333333, 0.533333333333333, 
    0.566666666666667, 0.666666666666667, 0.666666666666667, 
    0.666666666666667, 0.7, 0.666666666666667, 0.666666666666667, 
    0.633333333333333, 0.666666666666667, 0.733333333333333, 
    0.833333333333333, 0.9, 1.13333333333333, 1.3, 1.3, 1.36666666666667, 
    1.36666666666667, 1.7, 1.76666666666667, NA, NA, 0.5, 0.5, 
    0.466666666666667, 0.5, 0.5, 0.533333333333333, 0.533333333333333, 
    0.533333333333333, 0.6, 0.7, 0.633333333333333, 0.666666666666667, 
    0.666666666666667, 0.7, 0.7, 0.666666666666667, 0.733333333333333, 
    0.8, 0.866666666666667, 0.9, 0.866666666666667, 1.03333333333333, 
    1.13333333333333, 1.2, 1.5, 1.4, 1.8, NA, 0.533333333333333, 
    0.5, 0.5, 0.5, 0.5, 0.5, 0.533333333333333, 0.533333333333333, 
    0.566666666666667, 0.7, 0.666666666666667, 0.666666666666667, 
    0.666666666666667, 0.666666666666667, 0.733333333333333, 
    0.8, 0.933333333333333, 0.866666666666667, 0.9, 0.966666666666667, 
    0.933333333333333, 0.966666666666667, 1.16666666666667, 1.16666666666667, 
    1.16666666666667, 1.2, 1.36666666666667, 1.33333333333333, 
    NA, 0.533333333333333, 0.533333333333333, 0.5, 0.5, 0.5, 
    0.5, 0.6, 0.566666666666667, 0.633333333333333, 0.666666666666667, 
    0.666666666666667, 0.666666666666667, 0.666666666666667, 
    0.733333333333333, 0.766666666666667, 0.833333333333333, 
    0.9, 1.03333333333333, 0.966666666666667, 0.966666666666667, 
    0.933333333333333, 1.03333333333333, 1.1, 1.5, 1.53333333333333, 
    1.26666666666667, 1.5, 1.5, NA, 0.566666666666667, 0.533333333333333, 
    0.533333333333333, 0.5, 0.5, 0.5, 0.5, 0.6, 0.666666666666667, 
    0.666666666666667, 0.666666666666667, 0.666666666666667, 
    0.666666666666667, 0.766666666666667, 0.766666666666667, 
    0.833333333333333, 0.9, 1, 0.966666666666667, 0.966666666666667, 
    0.966666666666667, 1.03333333333333, 1.16666666666667, 1.6, 
    1.16666666666667, 1.23333333333333, 1.56666666666667, 1.5, 
    0.566666666666667, 0.566666666666667, 0.566666666666667, 
    0.533333333333333, 0.533333333333333, 0.533333333333333, 
    0.5, 0.533333333333333, 0.633333333333333, 0.633333333333333, 
    0.633333333333333, 0.633333333333333, 0.633333333333333, 
    0.733333333333333, 0.8, 0.833333333333333, 0.9, 1, 1.03333333333333, 
    1, 1, 1, 1.26666666666667, 1.26666666666667, 1.3, 1.53333333333333, 
    1.4, 1.56666666666667, 1.93333333333333, 0.6, 0.566666666666667, 
    0.6, 0.566666666666667, 0.566666666666667, 0.566666666666667, 
    0.566666666666667, 0.566666666666667, 0.666666666666667, 
    0.666666666666667, 0.666666666666667, 0.633333333333333, 
    0.766666666666667, 0.8, 0.9, 0.933333333333333, 0.933333333333333, 
    1.06666666666667, 1.13333333333333, 1.1, 1.03333333333333, 
    0.966666666666667, 1.16666666666667, 1.43333333333333, 1.46666666666667, 
    1.33333333333333, 1.43333333333333, 1.63333333333333, 1.7, 
    NA, NA, 0.666666666666667, 0.666666666666667, 0.666666666666667, 
    0.666666666666667, 0.6, 0.633333333333333, 0.766666666666667, 
    0.733333333333333, 0.8, 0.833333333333333, 0.9, 0.933333333333333, 
    0.933333333333333, 0.933333333333333, 0.966666666666667, 
    1.1, 1.16666666666667, 1.1, 1.06666666666667, 1.23333333333333, 
    1.43333333333333, 1.4, 1.73333333333333, 1.43333333333333, 
    1.36666666666667, 1.46666666666667, 2.03333333333333, NA, 
    NA, 0.733333333333333, 0.8, 0.766666666666667, 0.733333333333333, 
    0.8, 0.866666666666667, 0.9, 0.966666666666667, 1, 1, 1.06666666666667, 
    0.933333333333333, 0.933333333333333, 0.933333333333333, 
    1, 1.2, 1.2, 1.06666666666667, 1.13333333333333, 1.13333333333333, 
    1.2, 1.26666666666667, 1.36666666666667, 1.4, 1.43333333333333, 
    1.43333333333333, 2.2, NA, NA, 0.866666666666667, 0.933333333333333, 
    0.9, 0.933333333333333, 0.933333333333333, 1, 1.03333333333333, 
    1.03333333333333, 1, 1.03333333333333, 1.23333333333333, 
    1.26666666666667, 0.966666666666667, 0.966666666666667, 1.03333333333333, 
    1.3, 1.13333333333333, 1.33333333333333, 1.1, 1.16666666666667, 
    1.26666666666667, 1.43333333333333, 1.33333333333333, 1.5, 
    1.43333333333333, 1.4, 1.46666666666667, NA, NA, 1.03333333333333, 
    1.06666666666667, 0.966666666666667, 1.1, 1.06666666666667, 
    1.03333333333333, 1.13333333333333, 1.13333333333333, 1.1, 
    1.16666666666667, 1.2, 1.3, 1.23333333333333, 1.03333333333333, 
    1.03333333333333, 1.26666666666667, 1.53333333333333, 1.13333333333333, 
    1.1, 1.26666666666667, 1.26666666666667, 1.33333333333333, 
    1.36666666666667, 1.4, 1.43333333333333, 1.53333333333333, 
    1.56666666666667), offset = 0, gain = 1, inmemory = TRUE, 
        fromdisk = FALSE, isfactor = FALSE, attributes = list(), 
        haveminmax = TRUE, min = 0.266666666666667, max = 3, 
        band = 1L, unit = "", names = "mean_cold_events"), legend = new(".RasterLegend", 
        type = character(0), values = logical(0), color = logical(0), 
        names = logical(0), colortable = logical(0)), title = character(0), 
    extent = new("Extent", xmin = 145.9249999999, xmax = 147.3749999999, 
        ymin = -35.5249999999999, ymax = -33.475), rotated = FALSE, 
    rotation = new(".Rotation", geotrans = numeric(0), transfun = function () 
    NULL), ncols = 29L, nrows = 41L, crs = new("CRS", projargs = NA_character_), 
    history = list(), z = list())

installation on CentOS 7 "initGEOS_r not found in libgeos_c"

I've attempted to install exactextractr but have had no luck. I'm on CentOS and have rebuilt most of the geospatial tools from Fedora, including GDAL-2.3.1-3 and geos-3.6.1-10, and installed these along with developmental libraries and headers. I've verified the locations of geos-config and libgeos_c, and that initGEOS_r exists in libgeos_c, but to no avail. I've also tried multiple versions and methods of installing geos, but each had the same result. Lastly, this same error can be found associated with rgeos and other R geospatial packages, but the solutions are varied (often involving installing an older rgeos) and none of these solutions have worked for me.

 * installing *source* packageexactextractr...                                                                                                                                                                 
 ** packageexactextractrsuccessfully unpacked and MD5 sums checked                                                                                                                                             
 ** using staged installation                                                                                                                                                                                      
 configure: exactextractr: 0.1.0                                                                                                                                                                                   
 checking for geos-config... /usr/bin/geos-config                                                                                                                                                                  
 checking geos-config usability... yes                                                                                                                                                                             
 configure: GEOS version: 3.6.1                                                                                                                                                                                    
 checking geos version at least 3.5.0... yes                                                                                                                                                                       
 checking compiling and building against geos_c... no                                                                                                                                                              
 checking geos: linking with -L/usr/lib64 -lgeos_c -lgeos -lm... no                                                                                                                                                
 ./configure: line 1854: -o: command not found                                                                                                                                                                     
 configure: Compilation and/or linkage problems.                                                                                                                                                                   
 configure: error: initGEOS_r not found in libgeos_c.                                                                                                                                                              
 ERROR: configuration failed for packageexactextractr'
nm -D /usr/lib64/libgeos_c.so | grep initGEOS

000000000000f190 T initGEOS
0000000000010cc0 T initGEOS_r

any help is appreciated! the raster package is simply too slow. FWIW I've successfully installed sf, sp, raster, rgdal, rgeos, gdalUtils, etc etc and every geospatial package save this one installs successfully, so it may be something with exactextractr's configure script (I saw recent updates attempting to resolve a problem with geos).

v/r,
Chandler

Wrong mean for a raster with units of meters

HI, I tested if "exactextract" worked correctly on Daymet data, which is a raster data with its unit of meters.
I prepared a Shapefile of a polygon which covers exactly 2 Daymet cells as test data (the polygon in this Shapefile has WGS84 as its CRS), and compared the result of exactextract and that calculated manually (since it covers exactly 2 cells, I can compute the mean by extracting the precipitation values of these 2 cells).
The true (manually computed) result is (10.0 + 10.0)/2 = 10.0 mm, but the result from exactextract is 29.16989 mm (whether or not I re-projected the Shapefile into the same units of meters through the CRS used in the Daymet raster data).

Is this a bug of "exactextractr"? Or is "exactextractr" not applicable to rasters in meters as its unit?

Possibility to add additional Statistics

Hi,

thanks for this: really helpful and fast!

Since I am in the process of "switching" my "R" packages to usage of exact_extractr (abandoning velox, or "standard" raster::extract): would it be possible/useful to include additional statistic indicators, such as variance/standard deviation/variation coefficient ? I know I can extract all "pixel" values and then compute them myself, but I think having them ready-made could be useful.

HTH,

Lorenzo

Error during install using devtools on Windows machine

I keep getting the error below when trying to install this package on my Windows machine. I have installed the rgeos and devtools packages. Any advice is appreciated!

`> install_github('isciences/exactextractr')
Downloading GitHub repo isciences/exactextractr@master

checking for file 'C:\Users\masonl\AppData\Local\Temp\1\RtmpSwJxKY\remotes8943ce5204\isciences-exactextractr-37c2f0f/DESCRIPTION' ...

checking for file 'C:\Users\masonl\AppData\Local\Temp\1\RtmpSwJxKY\remotes8943ce5204\isciences-exactextractr-37c2f0f/DESCRIPTION' ...

√ checking for file 'C:\Users\masonl\AppData\Local\Temp\1\RtmpSwJxKY\remotes8943ce5204\isciences-exactextractr-37c2f0f/DESCRIPTION' (642ms)

  • preparing 'exactextractr': (658ms)

    checking DESCRIPTION meta-information ...

    checking DESCRIPTION meta-information ...

√ checking DESCRIPTION meta-information

  • cleaning src
  • checking for LF line-endings in source and make files and shell scripts (1.2s)
  • checking for empty or unneeded directories (413ms)
  • building 'exactextractr_0.1.0.tar.gz'

Warning:
Warning: file 'exactextractr/cleanup' did not have execute permissions: corrected

Warning:

Warning: file 'exactextractr/configure' did not have execute permissions: corrected

  • installing source package 'exactextractr' ...


    WARNING: this package has a configure script
    It probably needs manual configuration


** libs

*** arch - i386
rm -f exactextractr.dll RcppExports.o exact_extract.o exactextract/src/cell.o exactextract/src/geos_utils.o exactextract/src/floodfill.o exactextract/src/box.o exactextract/src/area.o exactextract/src/side.o exactextract/src/traversal_areas.o exactextract/src/extent.o exactextract/src/perimeter_distance.o exactextract/src/traversal.o exactextract/src/raster_cell_intersection.o exactextract/src/coordinate.o
mkdir -p ../inst
"C:/Users/masonl/DOCUME1/R/R-351.2/bin/i386/Rscript.exe" --vanilla "../tools/winlibs.R" 2.2.3
trying URL 'https://github.com/rwinlib/gdal2/archive/v2.2.3.zip'
Content type 'application/zip' length 44034709 bytes (42.0 MB)

downloaded 42.0 MB

C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c RcppExports.cpp -o RcppExports.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exact_extract.cpp -o exact_extract.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/cell.cpp -o exactextract/src/cell.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/geos_utils.cpp -o exactextract/src/geos_utils.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/floodfill.cpp -o exactextract/src/floodfill.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/box.cpp -o exactextract/src/box.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/area.cpp -o exactextract/src/area.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/side.cpp -o exactextract/src/side.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/traversal_areas.cpp -o exactextract/src/traversal_areas.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/extent.cpp -o exactextract/src/extent.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/perimeter_distance.cpp -o exactextract/src/perimeter_distance.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/traversal.cpp -o exactextract/src/traversal.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/raster_cell_intersection.cpp -o exactextract/src/raster_cell_intersection.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -I"C:/Users/masonl/DOCUME1/R/R-351.2/include" -DNDEBUG -I"C:/Users/masonl/Documents/R/R-3.5.2/library/Rcpp/include" -std=c++14 -I../windows/gdal2-2.2.3/include/geos -O2 -Wall -mtune=generic -c exactextract/src/coordinate.cpp -o exactextract/src/coordinate.o
C:/RBuildTools/3.5/mingw_32/bin/g++ -shared -s -static-libgcc -o exactextractr.dll tmp.def RcppExports.o exact_extract.o exactextract/src/cell.o exactextract/src/geos_utils.o exactextract/src/floodfill.o exactextract/src/box.o exactextract/src/area.o exactextract/src/side.o exactextract/src/traversal_areas.o exactextract/src/extent.o exactextract/src/perimeter_distance.o exactextract/src/traversal.o exactextract/src/raster_cell_intersection.o exactextract/src/coordinate.o -lgeos_c -lgeos -L../windows/gdal2-2.2.3/lib-4.9.3/i386 -LC:/Users/masonl/DOCUME1/R/R-351.2/bin/i386 -lR
C:/RBuildTools/3.5/mingw_32/bin/../lib/gcc/i686-w64-mingw32/4.9.3/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -lgeos_c
C:/RBuildTools/3.5/mingw_32/bin/../lib/gcc/i686-w64-mingw32/4.9.3/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -lgeos
collect2.exe: error: ld returned 1 exit status
no DLL was created
ERROR: compilation failed for package 'exactextractr'

  • removing 'C:/Users/masonl/Documents/R/R-3.5.2/library/exactextractr'
    In R CMD INSTALL
    Error in i.p(...) :
    (converted from warning) installation of package ‘C:/Users/masonl/AppData/Local/Temp/1/RtmpSwJxKY/file8946682340/exactextractr_0.1.0.tar.gz’ had non-zero exit status
    In addition: Warning messages:
    1: In untar2(tarfile, files, list, exdir) :
    skipping pax global extended headers
    2: In untar2(tarfile, files, list, exdir) :
    skipping pax global extended headers
    `

NaN values in extraction

I am trying to use exact_extract function where the shapefile is the one used in the Basic Usage section of the readme file

# Pull municipal boundaries for Brazil
brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

I have the following RasterLayer:

my_raster   <- raster::raster(ncfname)
str(my_raster)
Formal class 'RasterLayer' [package "raster"] with 12 slots
  ..@ file    :Formal class '.RasterFile' [package "raster"] with 13 slots
  .. .. ..@ name        : chr "xxxx"| __truncated__
  .. .. ..@ datanotation: chr "FLT4S"
  .. .. ..@ byteorder   : chr "little"
  .. .. ..@ nodatavalue : num -32767
  .. .. ..@ NAchanged   : logi FALSE
  .. .. ..@ nbands      : int 6552
  .. .. ..@ bandorder   : chr "BIL"
  .. .. ..@ offset      : int 0
  .. .. ..@ toptobottom : logi FALSE
  .. .. ..@ blockrows   : int 0
  .. .. ..@ blockcols   : int 0
  .. .. ..@ driver      : chr "netcdf"
  .. .. ..@ open        : logi FALSE
  ..@ data    :Formal class '.SingleLayerData' [package "raster"] with 13 slots
  .. .. ..@ values    : logi(0) 
  .. .. ..@ offset    : num 0
  .. .. ..@ gain      : num 1
  .. .. ..@ inmemory  : logi FALSE
  .. .. ..@ fromdisk  : logi TRUE
  .. .. ..@ isfactor  : logi FALSE
  .. .. ..@ attributes: list()
  .. .. ..@ haveminmax: logi FALSE
  .. .. ..@ min       : num Inf
  .. .. ..@ max       : num -Inf
  .. .. ..@ band      : int 112
  .. .. ..@ unit      : chr "m**3 m**-3"
  .. .. ..@ names     : chr "xxxx"
  ..@ legend  :Formal class '.RasterLegend' [package "raster"] with 5 slots
  .. .. ..@ type      : chr(0) 
  .. .. ..@ values    : logi(0) 
  .. .. ..@ color     : logi(0) 
  .. .. ..@ names     : logi(0) 
  .. .. ..@ colortable: logi(0) 
  ..@ title   : chr(0) 
  ..@ extent  :Formal class 'Extent' [package "raster"] with 4 slots
  .. .. ..@ xmin: num -55
  .. .. ..@ xmax: num -45
  .. .. ..@ ymin: num -17.1
  .. .. ..@ ymax: num -12.9
  ..@ rotated : logi FALSE
  ..@ rotation:Formal class '.Rotation' [package "raster"] with 2 slots
  .. .. ..@ geotrans: num(0) 
  .. .. ..@ transfun:function ()  
  ..@ ncols   : int 101
  ..@ nrows   : int 41
  ..@ crs     :Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
  ..@ history : list()
  ..@ z       :List of 1
  .. ..$ : chr "2019-01-05 16:06:28"

Then i run the exact_extract function

brazil$mean <- (brazil, my_raster, 'mean')

which returns me NaN values, as shown below

image

Am i doing something wrong importing the raster or this is a known issue in the package?

sfc_GEOMETRY not accomodated

Hi, when the class of the geometry is sfc_GEOMETRY instead of (MULTI)POLYGON (in your vignette example it is a multipolygon), the function fails with error message

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘exact_extract’ for signature ‘"RasterLayer", "sfc_GEOMETRY"’

exact_resample with fun = 'mode' returns only NAs

Hello,

I just discovered the exactextractr::exact_resample() function. It works perfectly fine with the stats "mean", "sum", "count", "min", and "max". However, it always returns only NAs when using stats "mode" or "minority", e.g.:

r = raster::raster(resolution = 2)
target = raster::shift(r, 2.5, 1)

set.seed(1111)
raster::values(r) = as.integer(round(rnorm(raster::ncell(r), 0, 1)))

unique(raster::getValues(exactextractr::exact_resample(r, target, fun = "mode")))
[1] NA
unique(raster::getValues(exactextractr::exact_resample(r, target, fun = "min")))
[1]  1  0 -3 -1 -2  2 NA -4

Need to update exactextract subtree

Recent commits in exactextract code allow us to control memory usage by processing large polygons in multiple passes, and prevent at least one potential crash. This subtree needs be updated (a significant effort, given API changes in exactextract)

Output Order

I've been looking for a way to easily join the outputs of this processing back to the input shapefile.

If the output is in the same order as the polygons in the shapefile, then the solution is simple, but I don't see a guarantee or explanation of the ordering in the documentation.

Could you clarify what the output ordering is?

submitted sf will break exactextractr on CRAN

With new sf, we see

st_crs("+proj=longlat +datum=WGS84 +no_defs")$epsg

resulting in NA rather than 4326. This is GDAL, trying to guess the epsg from the WKT representation of the proj4string. I think this is wrong, but cannot be resolved by sf. In any case, it causes errors in your tests, and errors on CRAN once sf gets accepted. See https://win-builder.r-project.org/incoming_pretest/sf_0.9-0_20200319_213604/reverseDependencies/summary.txt and https://www.r-spatial.org/r/2020/03/17/wkt.html

Support `RasterStack` inputs

This would be useful to calculate quantities such as the percentage of population in a boundary that is experiencing drought, with population and drought provided as a RasterStack.

Weighted_sum is giving weird results

Hello!

I am using weighted_sum function in calculating the total population of each parish in Uganda (named parish) using population count raster file (named) from worldpop. I tried to both:

  1. exact_extract(population,parish, 'weighted_sum', weights = area(population))
  2. exact_extract(population,parish, 'sum')

They returned very different results: weighted_sum has max of ~500, sum has max of ~67,000. Summing across all parishes population, neither of the total population in the country calculated from method 1 and method 2 is consistent with the sum of the original raster file.

I also tried to test weighted_sum function using the brazil example, simple sum and weighted_sum are producing really different results. I am wondering what might go wrong.

I am using Mac Big Sur system, R and exactextractr package are both at current version. Your help is greatly appreciated!

Expose weighted variations of statistics

The command-line exactextract can process two rasters simultaneously and perform predefined summary statistics, such as weighted_mean. This functionality should be exposed in exactextractr, by a variation of exact_extract that takes two RasterLayers and one sf.

Standard deviation

Dear,

Thanks for this package. Its so fast.

There is a way to evaluate standard deviation, range and median with this package?

Thanks a lot

Best wishes

Summarizing categorical data

Hello,

I tried to use the summarize_df=T feature in the exact_extract() function, but using your own examples from within the package vignettes:

landcov_fracs <- exact_extract(clc, concelhos, function(df) {
    df %>%
      mutate(frac_total = coverage_fraction / sum(coverage_fraction)) %>%
      group_by(name, value) %>%
      summarize(freq = sum(frac_total))
  }, summarize_df = TRUE, include_cols = 'name', progress = FALSE)

I get the following error:

Error in .exact_extract(x, y, fun = fun, ..., include_xy = include_xy, :
exact_extract was called with a function that does not appear to be of the form function(values, coverage_fractions, ...)

I have updated all my R packages, am using R version 4.0.4 and have just installed the recent package version from Github.

Generating percentage cover by value type, within a polygon

If I have a raster that contain cells with integer values that represent categorical variables (say 1 to 10), and I'd like to know the percentage cover for each value type, from a subset of the raster as determined by an sf polygon, how should I go about doing this? I'd like to return a vector containing percentages (one for each value type), for a given bounding polygon. I thought it would be something along the lines of:

exact_extract(raster, poly_sf, function(value) count(value)/no_of_cells_in_poly_sf)

But I'm not sure how to extend this to return a vector for the % cover for each value type. Thank you

applying functions before summary

Can I apply a math function (e.g. log or sin) to raster values after the extraction with polygons and before a summary operation (e.g. sum, mean) is done? The reason I ask for that is sometime I have very large original raster files (GB to 10s of GB) and I want to extract values with a number of small polygons. If I apply these preprocessing functions directly to the original rasters, it will take forever. But after extraction to the individual polygon extent, it should be much easier. If that functionality does NOT exist, could you add it in?

Enable predefined statistics for RasterStacks

Currently, exactextractr only allows the use of predefined statistics ('min', 'max', etc.) on RasterLayers. This could be expanded to support RasterStack and RasterBrick to avoid computing a coverage fraction for each layer of a stack.

Stand alone function to generate weight table?

Greetings!

I've been working on a project over here: https://github.com/USGS-R/intersectr that implements a similar workflow to exactextractr but, so far, focuses on low-enough resolution grids that it is not unreasonable to represent them as cell geometry. I currently have handling for curvilinear and Rectilinear NetCDF Grids. I hope to expand support to include high-res rectilinear Raster grids a la Zonal Stats as well as ad-hoc polygon coverages.

For performance and flexibility, the workflow in intersectr uses cacheable files that contain "cell geometry" -> "area weights" -> "extracted data" -- I mention this to illustrate that I generate a table containing the area weights for each combination of input data source cell and destination geometry. The area weights uses an ID assigned by row so 1 is the upper left and nrow*ncol is lower right.

Would you be interested in exporting a function that could generate such area weights? I'm hoping to get intersectr to CRAN too... maybe we could team up? Really like the exactextractr method!!

NA values is removed arbitrarily

I found that NA values is removed arbitrarily.
This is not desired for regional ET, GPP statistics. In this situation, NA values should be regarded as zero.

Hope users could have the options to remove NA values or replace them with zero. Or the give the notice in the exact_extract description.

extract data using POINT geometry type

I want to extract data from a raster (stack) using an sf object with POINT geometry types and get the error: Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘exact_extract’ for signature ‘"RasterLayer", "sfc_POINT"’

hence I assume this is not supported (yet). Is this correct and if so, would it be possible to add this feature?

weighted.mean does not work with raster stacks/bricks

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

Problem installing on MacOS

I tried to install and I get the following error msg:

exact_extract.cpp:18:10: fatal error: 'geos_c.h' file not found
#include <geos_c.h>
^~~~~~~~~~
1 error generated.
make: *** [exact_extract.o] Error 1
ERROR: compilation failed for package ‘exactextractr’

  • removing ‘/Library/Frameworks/R.framework/Versions/3.5/Resources/library/exactextractr’
    Installation failed: Command failed (1)

Any idea what's the problem and how to fix it? Thanks!

Install error

I'm getting the following error when I try to install "exactextractr".

exactextract/src/raster_stats.h:271:68: note: candidate: exactextract::RasterStats<T>::minority() const::<lambda(const int&, const int&)> [with T = double]
                                     [](const auto &a, const auto &b) {
                                                                    ^
exactextract/src/raster_stats.h:271:68: note:   no known conversion for argument 1 from ‘const std::pair<const double, float>’ to ‘const int&’
make: *** [exact_extract.o] Error 1
ERROR: compilation failed for package ‘exactextractr’

I'm on RHEL 7.8 using GCC 6.3.0 with R 4.0.3. Any ideas as to what's causing the error? Thanks!

Weighting example gives error

I was trying to implement your weighting example, but doing so get an error message:
I ran the following code:

library(raster)
library(sf)
library(exactextractr)

# Pull municipal boundaries for Brazil
brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

# Pull gridded precipitation data
prec <- getData('worldclim', var='prec', res=10)[[12]]

# Weighting
brazil$mean_prec_weighted <- exact_extract(prec, brazil, 'weighted_mean', weights=area(prec))

And receive the following error:

Error in .local(x, y, ...) :
exact_extract was called with a named summary operation thatdoes not accept additional arguments ...

Parse Exception ERROR, Unknown WKB type 235

I'm getting the following error when trying to get the coverage fraction from a .kml that has multiple holes in it (multipolygon?).
Same code works fine if the kml is simple (no holes in the middle).

Since I have no idea what the error means: what should I try first? Redraw the KML ?

> cov_frac <- coverage_fraction(x = rast, y = poly, crop=TRUE)
**Error in CPP_coverage_fraction(x, wkb, crop) :   ParseException: Unknown WKB type 235**

GithubExample

"count" as summary

Can you give an example of using "count" as the summary operation. I'm not sure what the correct grammar is.
exact_extract(rast, poly,'count', const), where const the the cell value I want to count? Also, what if I want to count cells with the value large than a given value?

Extraction of weighted mean from raster generating “row <= x@nrows is not TRUE” error

Hi,
I am using the exactextractr R package to calculate the mean value of raster cells overlapped by a set of multi-polygon geometries (each multi-polygon represents the distribution of a species).

Here, the example files.

Since the raster is in geographic coordinates and the cells don't have all the same area, I actually need to calculate the weighted mean of the raster values, using the coverage fraction and the cell area as weights. So:

I read the raster and the shapefile:

#Read the raster
r <- raster("raster.grd")
r
class : RasterLayer
dimensions : 278, 715, 198770 (nrow, ncol, ncell)
resolution : 0.5, 0.5 (x, y)
extent : -179, 178.5, -55.5, 83.5 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
source : C:/Users/MS/Analysis/raster.grd
names : w001001
values : 0, 81.45476 (min, max)

#Read the shapefile
all <- st_read(dsn = 'all.shp')
Reading layer all' from data source C:\Users\MS\Analysis\all.shp' using
driver `ESRI Shapefile'
Simple feature collection with 5 features and 1 field
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -180 ymin: -23.60646 xmax: 180 ymax: -4.725997
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs

Then, following the package instructions, I create a two-layer RasterStack, with the first layer containing my raster and the second layer containing the area of each cell:

#Create stack
stk <- stack(list(r= r, a= area(r)))

Finally, I used the exact_extract function from the exactextractr package, with a customized function to calculate the weighted mean:

all$wm <- exact_extract(stk, all, function(values, coverage_frac)
weighted.mean(values$r, values$a*coverage_frac, na.rm = T))
| | 0%

but I obtained the following error:

Error in .local(x, ...) : row <= x@nrows is not TRUE

The error is due to a single geometry(field "scntfcN" = Mirimiri acrodonta, here the shapefile).

It's a tiny multipolygon located on the Fiji Island (a theoretically single polygon split into two by the anti-meridian line) not intersecting the original raster.

Strangely, if I try to calculate the (no-weighted) mean through the predefined function of the package, it works well:

all$m <- exact_extract(r, all, 'mean')
returning NaN for the problematic geometry (since it doesn't intersect the raster)

What could be the cause of the error?

Thanks,
NB

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.