Reputation: 1327
I have a raster and sf
polygon as follows:
library(raster)
libary(sf)
# Create raster r
r = raster(ncol=1000, nrow=1000, xmn=0, xmx=1000, ymn=0, ymx=1000)
values(r) = round(runif(ncell(r),1,10))
# Create sf polygon
poly_sf = st_sfc(st_polygon(list(cbind(c(0,10,50,100,0),c(0,70,300,500,0)))))
The raster contains cells of values between 1 and 10. I'd like to be able to generate a dataframe that contains the overall percentage of total cells for each value, within a subset of raster cells generated by the polygon poly_sf
. I've looked at exactextractr
but haven't figured out how to achieve what I want using that package.
Upvotes: 2
Views: 1220
Reputation: 16178
You can have the use of mask
function from raster
package but you need to convert your polygon into an sf
object:
library(raster)
library(sf)
# Create raster r
r = raster(ncol=1000, nrow=1000, xmn=0, xmx=1000, ymn=0, ymx=1000)
values(r) = round(runif(ncell(r),1,10))
# Create sf polygon
poly_sf = st_sfc(st_polygon(list(cbind(c(0,10,50,100,0),c(0,70,300,500,0)))))
p2 <- st_as_sf(poly_sf)
# Plot the raster object:
plot(r)
You can create a mask using the mask
function:
plot(mask(r, p2))
So, to extract values from this masked object, you can use mask
function and count for proportions of each values using table
:
# Subset the polyfon from the SF object:
subset_ra <- mask(r, p2)
# Calculate the porportion of each value
df <- as.data.frame(table(as.matrix(subset_ra)))
df$Percent <- df$Freq / sum(df$Freq) * 100
Var1 Freq Percent
1 1 154 5.517736
2 2 329 11.787890
3 3 287 10.283053
4 4 290 10.390541
5 5 325 11.644572
6 6 305 10.927983
7 7 319 11.429595
8 8 312 11.178789
9 9 315 11.286277
10 10 155 5.553565
Does it answer your question ?
Upvotes: 3