简体   繁体   中英

How to extract from a .nc file based on a shapefile in R?

I have a .nc file which has global data and I want to extract the data which are within the boundary of a .shp file. I have tried several methods, but still have some problems.

The .nc file can be downloaded at https://www.dropbox.com/s/0ba6v4fnck8wjdm/spei03.nc?dl=0 and the .shp file can be downloaded at https://www.dropbox.com/s/8wfgf8207dbh79r/gpr_000b11a_e.zip?dl=0

library(rgdal)
library(ncdf4)
library(raster)

shpfile<-readOGR("gpr_000b11a_e.shp", layer="gpr_000b11a_e")
g <- spTransform(shpfile, CRS("+proj=aea +lat_1=50 +lat_2=70 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0"))
ncdata = raster(x="spei03.nc",varname="spei")
proj4string(ncdata) = proj4string(g)
Mydata = rasterToPoints(mask(x=ncdata,mask = g))

But then I cannot get any data. Thanks for any help.

To extract values, use extract() function. But, you need to select what time step you want to use:

library(ncdf4)
library(raster)

shpfile<-shapefile("gpr_000b11a_e.shp") # load shapefile

spei_nc=nc_open("spei03.nc") # open .nc data
mtrx <- ncvar_get(spei_nc, varid="spei")[,,3] # extact value. In this case, 3 is for time step number 3

spei_r <- raster(t(mtrx),xmn=-180, xmx=180, ymn=-90, ymx=90) # create a raster with data (it is flipped)
spei_r <- flip(spei_r,2) # correct raster
projection(spei_r) <- '+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 ' # add CRS

plot(spei_r) # check result

在此处输入图片说明

# reproject shapefile
g <- spTransform(shpfile, spei_r@crs)

# extract values by ecah feature
spei_values <- extract(spei_r,g)

# extract mean by each feature
spei_mean <- extract(spei_r,g,fun=mean,na.rm=T)

spei_mean
##              [,1]
##  [1,] -0.37517873
##  [2,]  0.24568238
##  [3,]  0.12212451
##  [4,] -1.44496705
##  [5,]  0.57723304
##  [6,]  0.08963697
##  [7,]  0.07029936
##  [8,]  0.01176584
##  [9,]  0.35061048
## [10,]  0.09197929
## [11,]  0.41005611
## [12,]  0.19130312
## [13,] -0.69751740

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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