创建R循环以从目录中读取shapefile并对每个文件执行区域统计 [英] Creating R loop to read in shapefiles from a directory and perform zonal statistics on each

查看:59
本文介绍了创建R循环以从目录中读取shapefile并对每个文件执行区域统计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在县"目录中有120个县shapefile.我想使用R读取每个shapefile,并使用单个栅格图层"NOAA_normal_crop"对每个shapefile执行区域统计(均值).

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."

我能够创建一个脚本,该脚本以列表形式读取所有shapefile:

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)

但是我仍然需要创建一个循环,遍历每个单独的shapefile并执行区域统计.下面的循环是我尝试过的循环,但它只给我一个值,而我想要每个多边形的平均值.

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)
}

我也尝试过再次使用lapply,但这也不起作用.

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.

推荐答案

我相信您的循环是正确的.但是,它不是列表或数组,因此每次迭代都会覆盖该值.你应该试试:例如= vector()对于(i in 1:length(allShapes)){ex [i]<-提取(NOAA_normal_crop,allShapes [[i]],fun = mean,na.rm = TRUE,df = TRUE)}

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) }

这篇关于创建R循环以从目录中读取shapefile并对每个文件执行区域统计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆