如何根据R中的shapefile从.nc文件中提取?

时间:2017-09-13 21:34:12

标签: r spatial raster shapefile extraction

我有一个.nc文件,它有全局数据,我想提取.shp文件边界内的数据。我尝试了几种方法,但仍有一些问题。

.nc文件可以在https://www.dropbox.com/s/0ba6v4fnck8wjdm/spei03.nc?dl=0下载,.shp文件可以在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))

但是我无法得到任何数据。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

要提取值,请使用extract()功能。但是,您需要选择要使用的时间步长:

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

enter image description here

# 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
相关问题