如何在Windows 7上使用NCO或R将每月TRMM netCDF文件连接成一个netCDF文件?

时间:2016-10-05 18:22:48

标签: r concatenation netcdf nco

我已经从1998年到2016年以netCDF格式下载了TRMM月降水率,因此大约有200多个文件。这些文件的名称是3B43.19980101.7.HDF.nc 3B43.19980201.7.HDF.nc 3B43.19980301.7.HDF.nc,依此类推。 我想将所有这些文件连接成一个netCDF。我尝试过使用NCO运算符" ncrcat"它应该能够在记录维度上连接很长的一系列文件,在这种情况下是时间,但到目前为止还没有运气。我在第一次简单尝试只有2个文件

ncrcat -O -h 3B43.19980101.7.HDF.nc 3B43.19980201.7.HDF.nc out.nc

得到

  

错误:没有适合处理的变量标准

所以我尝试了

ncks --mk_rec_dmn time 3B43.19980101.7.HDF.nc TD.3B43.19980101.7.HDF.nc
ncks --mk_rec_dmn time 3B43.19980201.7.HDF.nc TD.3B43.19980201.7.HDF.nc

我再次尝试

ncrcat -O -h TD.3B43.19980101.7.HDF.nc TD.3B43.19980201.7.HDF.nc out.nc

仍有同样的错误

  

错误:没有适合处理的变量标准

使用200多个文件有更简单的方法吗?我可以遵循的脚本?我对这一切都是新手,所以请保持温柔。

非常感谢任何帮助。我使用的是Windows 7 x86。

2 个答案:

答案 0 :(得分:2)

使用NCO完全可以做到这一点。我看了你的输入文件,他们只是缺少时间维度,所以ncrcat失败了。使用

添加时间维度
ncecat -u time in.nc out.nc

然后如上所述使用ncrcat。附:我已经更改了ncrcat和ncra错误消息,以更明确地说明如何执行此操作。以前,HINT仅适用于文件已经具有维度的情况,但它已修复。您的文件没有时间维度,因此您发出的ncks命令无效。

编辑以显示循环:

要在循环中执行此操作或类似操作,请使用

之类的构造
for fl in `ls trmm*.nc`; do
    ncecat -u time ${fl} ${fl/trmm/trmm_new} # Base output name in input name
    ... # more processing
done

NCO手册中有许多使用文件循环的例子。

答案 1 :(得分:1)

在R中,您可以通过读入所有数据,组合成一个大的3d数组(latxlonxtime)来完成此操作。例如,array [,, 1]将是1998年1月的latxlon网格。然后可以将其保存为.rds格式以便在R中进一步使用,或者保存为netCDF文件,我不会覆盖但是有一些教程可以将R数组保存为.nc文件在线。

首先,创建一个.csv文件,其中包含您下载的所有文件名的单个列。一种简单的方法是ctrl-C键入输出' ls'在终端进入excel表。下面的代码逐个读入这些文件,将每个文件添加到数组中。

library(ncdf4)
library(abind)
filenames=read.csv('TRMM.filenames.csv',head=F) #read in filenames
filenames=as.character(filenames[,1]) #convert to 'character' format

n.lon=192 #input the correct #'s here, must be the same for all files
n.lat=94

NA.matrix=matrix(rep(NA,n.lon*n.lat),nrow=n.lon) #used to initialize
prcp=array(NA.matrix,c(n.lon,n.lat,1)) #n.lonxn.latx1 array of NA's to initialize
for (i in 1:length(filenames)){
  ncdata=nc_open(filenames[i]) #read in file i, assuming files are in same location as filenames.csv/your current working directory
  #ncdata=nc_open(paste(data.dir,filenames[i],sep="")) #if your data is in another directory than the filenames.csv file, you could read it in with this line instead
  nc=ncvar_get(ncdata,"precip") #check the .nc files to see what the variable name actually is; this reads in the variable "precip"
  prcp=abind(prcp,nc)
}
prcp=prcp[,,-1] #remove the NA.matrix used to initialize

dim(prcp) #check that the lonxlatxtime dimensions make sense
saveRDS(prcp,'TRMM.all.rds') #save as .rds file, or proceed to save it as .nc file, which takes a bit more work