问题
I have 120 county shapefiles in a directory "Counties". I want to use R to read in each shapefile and, for each shapefile, perform zonal statistics (mean) using a single raster layer "NOAA_normal_crop."
I was able to create a script that reads in all of the shapefiles as a list:
library(rgdal)
library(raster)
library(sf)
library(maptools)
NOAA_normal <- raster("C:/path/to/raster/noaa_normal.tif")
input_path <- "C:/path/to/Counties"
files <- list.files(dir, pattern="[.]shp$", full.names=TRUE)
allShapes <- lapply(files, readOGR)
But I still need to create a loop that goes through each individual shapefile and performs the zonal statistics. The loop below is one I tried, but it only gives me a single value in return whereas I want the mean value for each polygon.
for (i in 1:length(allShapes)){
ex <- extract(NOAA_normal_crop, allShapes[[i]], fun=mean, na.rm=TRUE, df=TRUE)
}
EDIT: I have also tried using lapply again, but this isn't working either.
lapply(allShapes, extract(NOAA_normal_crop, allShapes, fun=mean, na.rm=TRUE, df=TRUE))
# Error in round(y) : non-numeric argument to mathematical function
Thanks in advance for any advice you might have.
回答1:
I believe your loop is correct. However it is not a list or array, so every iteration the value is being overwritten.
You should try:
ex = vector()
for (i in 1:length(allShapes)){
ex[i] <- extract(NOAA_normal_crop, allShapes[[i]], fun=mean, na.rm=TRUE, df=TRUE)
}
来源:https://stackoverflow.com/questions/58187021/creating-r-loop-to-read-in-shapefiles-from-a-directory-and-perform-zonal-statist