如何从R中的栅格地图中提取特定区域数据

how to extract specific area data from a raster map in R

my_raster.tiff文件为2013年中国PM2.5浓度

我已将数据 (my_raster.tiff) 上传到 Github (https://github.com/lizhiwei1994/example_data/blob/main/my_raster.tiff) 以重现代码。

我想从中国栅格地图(my_raster.tiff)中提取北京(中国首都)的PM2.5平均浓度。

具体来说,代码应该返回一个值,可能是这样的:

data.frame(city = 'Beijing', PM2.5 = 56.66) # PM2.5 = 56.66 is a fake number made up by myself
     city PM2.5
1 Beijing 56.66

示例数据

library(terra)
f <- system.file("ex/elev.tif", package="terra")
pm <- rast(f)
names(pm) <- "PM2.5"

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)[1]
v$city = "Beijing"

解决方案

e <- extract(pm, v, fun=mean, na.rm=TRUE)    
data.frame(city=v$city, e[,-1,drop=FALSE])
#     city    PM2.5
#1 Beijing 467.1052