我具有如下栅格和sf
多边形:
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)))))
栅格包含值介于1到10之间的像元。我希望能够生成一个数据框,该数据框包含由多边形poly_sf
生成的栅格像元的子集内每个值的全部像元的总百分比。我看过exactextractr
,但还没有弄清楚如何使用该程序包实现我想要的功能。
您可以使用mask
包中的raster
函数,但需要将多边形转换为sf
对象:
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)
您可以使用mask
功能创建遮罩:
plot(mask(r, p2))
因此,要从此蒙版对象中提取值,可以使用mask
函数并使用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
它回答了您的问题吗?