I have a question related to this question. I have a gridded shapefile, which has 256 grid polygons. This shapefile represents an area of interest, and that area of interest also has a raster. I want to know fraction area of the each of the polygons covered by the raster pixels. I have two classes in the raster o and 1. So based on the number of cells that have a value one, the function will return a value telling me that, for example, 60% of grid polygon 1 are covered with raster pixels that have a value one and 40% of grid polygon 1 are covered by raster pixels that have value 0. For such a task, can I use the exactextractr package in R?

1 Answer 1


If your values are just 0 or 1, mathematically, the mean of the values within each polygon are the same as the proportion of 1's. Here is what you can do:


r <- raster("./layers/r.tif")
g <- read_sf("./layers/grid.gpkg")

# mean values by polygon
ex <- extract(r, g, fun=mean, na.rm=TRUE, df=TRUE)

# transform data into percent
results <- ex %>% mutate(Percent_0 = (1-r)*100) %>% mutate(Percent_1 = r*100)

 ID         r Percent_0 Percent_1
1  1 0.9774000   2.26000  97.74000
2  2 0.8338000  16.62000  83.38000
3  3 0.8945000  10.55000  89.45000

Here you can download the simple data to do so.

Hope it helps.

  • 2
    This assumes perfect overlap (ie, the cells nest perfectly within each polygon). If only small slivers of cells intersected the polygon boundaries this could equate to a notable bias. The exact_extract function returns the cell value along with the fraction of the cell that intersects the polygon. Oct 17, 2020 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.