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?
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:
library(raster) library(sf) 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) head(results) 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
Hope it helps.