my_raster.tiff
file is the PM2.5 concentration in China in 2013.
I've uploaded the data (my_raster.tiff) to Github (https://github.com/lizhiwei1994/example_data/blob/main/my_raster.tiff) in order to reproduce the code.
I want to extract the average concentration of PM2.5 in Beijing (the capital city of China) from China raster map (my_raster.tiff
).
Specifically, the code shold ruturn one value, maybe like this:
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
Example data
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"
Solution
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