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

Viewed 925

I have NetCDF file that has precipitation data for 38 years. I am using shapefile of my area to extract data for my interest region. 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. 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. 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.

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

enter image description here

1 Answers

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.

Related