原则上你已经完成了三分之二的工作。当然,你可以使用以下代码创建起始索引:
require(ncdf4)
ncFile <- nc_open( MyNetCDF )
LonStartIdx <- which( ncFile$dim$lon$vals == 355)
LatStartIdx <- which( ncFile$dim$lat$vals == 34.5)
将计数器做同样的处理。然后读取你想要的变量。
MyVariable <- ncvar_get( ncFile, varName, start=c( LonStartIdx, LatStartIdx), count=...)
然而就我所知,在你的情况下,你没有运气。读/写netcdf例程按顺序执行它们的操作。由于你的坐标经度从0-360,并且你有一个包含零子午线的框,因此你的网格环绕。
对于你来说(假设你没有太多数据),将整个网格读入R中,然后使用subset
或使用which
创建索引,在R中剪切出你的“框”可能更有意义。
ncFile <- nc_open( MyNetCDF )
LonIdx <- which( ncFile$dim$lon$vals > 355 | ncFile$dim$lon$vals < 10)
LatIdx <- which( ncFile$dim$lat$vals > 34.5 & ncFile$dim$lat$vals < 44.5)
MyVariable <- ncvar_get( ncFile, varName)[ LonIdx, LatIdx]
nc_close(ncFile)
备注:我更喜欢使用ncdf4
,我发现其语法更容易记住(而且相比我已经忘记的旧版netcdf R包还有其他优势...)
好的。评论不能像我需要的那么长,所以我更新了答案。没关系。让我们逐步回答这些问题。
- The
which
function way will work. I use it myself.
The data will be in a similar format as in the netcf file, but I am not too sure if there is some problem with the 0 meridian (I guess yes). You might have to swap the two halves by doing something like this (replace the corresponding line in the 2nd example)
LonIdx <- c(which( ncFile$dim$lon$vals > 355) , which( ncFile$dim$lon$vals < 10) )
This changes the order of the coordinate indices so that the Western part comes first and then the Eastern.
Reformatting everything to a 2x3 data frame is possible. Take the data my 2nd code example returns (will be a matrix, [lon x lat]. Also get the values of the coordinates from
lon <- ncFile$dim$lon$val[LonIdx]
(or how longitude is called in your example, same for lat
). Then assemble the matrix using
cbind( rep(lat, each=length(lon)), rep(lon,length(lat)), c(myVariable) )
The coordinates will of course be the same as in the netcdf file...
您需要对最后的cbind进行一致性检查,因为我只有大约98%的把握没有搞乱坐标。在我桌面上找到的R脚本中,我使用了循环,这是...邪恶的... 这种方法应该(有点?)更快,也更合理。
C
会以不同的方式处理...也许又是Fortran不同(我通常会尝试一下)。 - Joe W