简体   繁体   English

使用由 R 中的多个多边形组成的 shapefile 从 NetCDF 中提取数据?

[英]Extract data from NetCDF using shapefile that consist of mulitiple polygon in R?

I have NetCDF file that has precipitation data for 38 years.我有 NetCDF 文件,其中包含 38 年的降水数据。 I am using shapefile of my area to extract data for my interest region.我正在使用我所在地区的 shapefile 为我的兴趣区域提取数据。 when I used below code, I get the data corresponding to the grid points that falls inside the polygon.当我使用下面的代码时,我得到了与多边形内的网格点相对应的数据。 I am however, interested in extracting data based on each polygon of the shapefile (12 in this case) and save the data frame using name of the polygon.但是,我有兴趣根据 shapefile 的每个多边形(在本例中为 12 个)提取数据,并使用多边形的名称保存数据框。 Below is my sample code下面是我的示例代码

library(ncdf4)
library(rgdal)
library(raster)
library(maptools)
library(GISTools)

NC = brick("Daily_Pcp.nc")
Subbasin_SHP=readOGR("my_Shapefile.shp")
crs(NC)
crs(Subbasin_SHP)
SHP=spTransform(Subbasin_SHP, crs(NC))

Polygon_Names=my_shapefile$Subbasin # there are 12 polygon (subbasins) in my shapefile with specific name

PCP_Data=mask(NC, Subbasin_SHP)
DF=as.data.frame(PCP_Data, xy=TRUE)
DF_insidepoints=DF[complete.cases(DF),]
write.csv(DF_insidepoints, "DataForEntireShapefile.csv")

Here is the map of the shapefile with all polygons.这是带有所有多边形的 shapefile 的地图。 I want all the points data that fall in a particular polygon be saved on its polygon name.我希望将落在特定多边形中的所有点数据保存在其多边形名称中。 In total I should get 12 files using mask function where as each files has data corresponding to the grid points that falls within that polygon.总共我应该使用mask函数获得 12 个文件,其中每个文件都有对应于该多边形内的网格点的数据。

plot(Subbasin_SHP, col="gray", border="blue", axes=TRUE, pbg="white")
pointLabel(coordinates(Subbasin_SHP), labels = Subbasin_SHP$Subbasin) 

在此处输入图像描述

You can use extract function from raster package in combination with stack function.您可以将光栅包中的提取功能与堆栈功能结合使用。

NC=raster::stack("Daily_Pcp.nc") # Stack raster just like brick you did
Subbasin_SHP=readOGR("my_Shapefile.shp") # Read shape file
df=raster::extract(NC,Subbasin_SHP,fun=mean, na.rm=T) #Extract dataframe

Any other changes in the dataframe is your choice.数据框中的任何其他更改都是您的选择。 example row and column names.示例行名和列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM