繁体   English   中英

如何从R中基于shapefile的.nc文件提取?

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

我有一个具有全局数据的.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))

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

要提取值,请使用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

在此处输入图片说明

# 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

暂无
暂无

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

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