簡體   English   中英

如何使用 R 將區域從 shapefile 傳輸到 netcdf 文件?

[英]How to transfer regions from a shapefile to a netcdf file using R?

我有一個包含葉綠素數據的區域 netcdf 文件,並希望添加一個新變量“區域”來映射有關海洋區域的信息。 因此,對於每個坐標點,都會有該點所屬區域的信息。

因此,對於 netcdf 文件中位於地中海區域的所有點,變量“region”將包含值 0,對於位於北海區域的所有點,變量“region”將例如包含值 1 等等...

我發現了一個包含基於生物地球化學過程的海洋區域的 shapefile(朗赫斯特省)。 現在我想使用這個 shapefile 在 netcdf 文件中定義我的“區域”變量。 有誰知道我怎么能在 R 中做到這一點?

我認為我的問題與DKRZ的這篇文章很接近,但我不想只提取/屏蔽一個區域,而是 map 在 shapefile 中定義的所有區域。

這些文件可以在這里找到:

https://drive.google.com/file/d/1kgPpHFapmuclDyUvw2TH_10i018GE9YH/view?usp=sharing

https://drive.google.com/file/d/1WLYEUs6XllZv6i0xjRif-N0syhR2lX01/view?usp=sharing

已經非常感謝了!

編輯
我發現這篇文章幫助我解決了我的問題: https://www.r-bloggers.com/2014/05/converting-shapefiles-to-rasters-in-r/

這是我可以根據Map Lat/Lon Points to a Shape File in R 組合起來的 主要工作由over()完成,這需要幾分鍾。

library(ncdf4)
nc_data = nc_open('/mnt/d/Downloads/CCI_ALL-v5.0-MONTHLY.nc', T)    # write
lon = ncvar_get(nc_data, "lon")
lat = ncvar_get(nc_data, "lat")
library(rgdal)
shapefile = readOGR('/mnt/d/Downloads/Longhurst_world_v4_2010.shp')
grid = expand.grid(lon=lon, lat=lat)
coordinates(grid) = ~lon+lat
grid@proj4string = shapefile@proj4string
# for each grid point, find the province it belongs to (if available):
prov = over(grid, shapefile['ProvCode'])
# define dimensions for the new variable
londim = ncdim_def("lon", ncatt_get(nc_data, "lon")$units, lon)
latdim = ncdim_def("lat", ncatt_get(nc_data, "lat")$units, lat)
# define the new variable
region = ncvar_def("region", "", list(londim, latdim), prec="integer")
# add the new variable to the netCDF file
nc_data = ncvar_add(nc_data, region)
# write the variable's values to the file
ncvar_put(nc_data, region, prov$ProvCode)
nc_close(nc_data)

rgdal 版本等:

Loading required package: sp
rgdal: version: 1.4-8, (SVN revision 845)
 Geospatial Data Abstraction Library extensions to R successfully loaded
 Loaded GDAL runtime: GDAL 3.0.4, released 2020/01/28
 Path to GDAL shared files:
 GDAL binary built with GEOS: TRUE
 Loaded PROJ.4 runtime: Rel. 6.3.1, February 10th, 2020, [PJ_VERSION: 630]
 Path to PROJ.4 shared files: (autodetected)
 Linking to sp version: 1.3-2
OGR data source with driver: ESRI Shapefile
Source: "/mnt/d/Downloads/Longhurst_world_v4_2010.shp", layer: "Longhurst_world_v4_2010"
with 54 features
It has 2 fields

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM