简体   繁体   中英

Why is terra package dropping these values when using extract function?

I use terra package to extract pesticide application from raster files. In the extract step it seems that terra removes some rows. In this example there are 19 warnings where it says:

Failed to compute min/max, no valid pixels found in sampling. (GDAL error 1)

After the extract step I have fewer rows left and it seem to have dropped some rows.

This step worked fine using raster (from here Using raster to calculate the mean application and total application of pesticides, but numbers not adding up ) but it is unfortunately to slow given the amount of files I need to process.

Any ideas what this error means and how to solve it?

Here is the code:

## Terra ----

data(wrld_simpl)

## Need to create a SparVector for terra
wrld_simpl = vect(wrld_simpl)

r <- terra::rast("https://raw.github.com/hansronald/Pesticide-data/master/APR_Soybean_Glyphosate_2015_L.tif")

## Remove 
r <- terra::clamp(r, lower=0, values=FALSE)

# area is in ha (values in raster are kg / ha per year)
a <- terra::area(r, sum=FALSE, mask=TRUE) * 0.0001

## Get the total area that pesticide has been applied to
tot_area <- terra::extract(a, wrld_simpl, fun = sum, na.rm = TRUE)

## Calculate total application in each cell
rtot  <- r * a

## Calculate total application in each country
tot_app  <- terra::extract(rtot, wrld_simpl, fun = sum, na.rm = TRUE)

## Mean application rate in each country
mean_app <- terra::extract(r, wrld_simpl, fun = mean, na.rm = TRUE)

## Save data to corresponding country
world_data = data.frame(wrld_simpl$NAME, wrld_simpl$ISO3)
world_data = data.frame(world_data, mean_app, tot_app, tot_area)

This happens because some of the polygons are so small that they do not cover a raster cell. This has now been fixed in the development version (terra >= 1.2.8); but here is an alternative approach with the exactrextractr package --- this is fast and gets you a very precise estimate, which is especially relevant when your raster cells are relatively large as in this case (although wrld_simpl is rather imprecise).

library(raster)
library(sf)
library(exactextractr)
ra <- raster(a)
wsf = st_as_sf(wrld_simpl)
e <- exact_extract(ra, wsf, "sum")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM