使用RnetCDF打开和读取多个netcdf文件

时间:2013-10-29 09:38:54

标签: r netcdf

使用R,我试图打开我在一个文件夹中的所有netcdf文件(例如20个文件)读取单个变量,并创建一个data.frame组合所有文件中的值。我一直在使用RnetCDF来读取netcdf文件。对于单个文件,我使用以下命令读取变量:

library('RNetCDF')
nc = open.nc('file.nc')
lw = var.get.nc(nc,'LWdown',start=c(414,315,1),count=c(1,1,240))

414& 315是我想要提取的值的经度和纬度,240是时间步数。

我找到了this帖子,解释了如何打开多个文件。在它之后,我设法使用:

打开文件
 filenames= list.files('/MY_FOLDER/',pattern='*.nc',full.names=TRUE)
 ldf = lapply(filenames,open.nc)

但现在我被卡住了。我试过了

  var1= lapply(ldf, var.get.nc(ldf,'LWdown',start=c(414,315,1),count=c(1,1,240)))

但它不起作用。 增加的复杂性是每个nc文件具有不同的时间步长。所以我有两个问题:

1:如何打开所有文件,读取每个文件中的变量并将所有值组合在一个数据框中? 2:如何设置count中的最后一个维度以改变所有文件?

3 个答案:

答案 0 :(得分:3)

@mdsummer发表评论之后,我尝试了一个do循环,并设法完成了我需要的所有工作:

# Declare data frame
df=NULL

#Open all files
files= list.files('MY_FOLDER/',pattern='*.nc',full.names=TRUE)

# Loop over files
for(i in seq_along(files)) {
nc = open.nc(files[i])

# Read the whole nc file and read the length of the varying dimension (here, the 3rd dimension, specifically time)
lw = var.get.nc(nc,'LWdown')
x=dim(lw)

# Vary the time dimension for each file as required
lw = var.get.nc(nc,'LWdown',start=c(414,315,1),count=c(1,1,x[3]))

# Add the values from each file to a single data.frame
rbind(df,data.frame(lw))->df
}

可能有更优雅的方式,但它有效。

答案 1 :(得分:0)

您传递的附加功能参数错误。您应该使用...。以下是如何将na.rm传递给mean的简单示例。

x.var <- 1:10
x.var[5] <- NA
x.var <- list(x.var)
x.var[[2]] <- 1:10
lapply(x.var, FUN = mean)
lapply(x.var, FUN = mean, na.rm = TRUE)

修改

对于您的具体示例,这将是

的内容
var1 <- lapply(ldf, FUN = var.get.nc, variable = 'LWdown', start = c(414, 315, 1), count = c(1, 1, 240))

虽然这是未经测试的。

答案 2 :(得分:0)

我认为使用CDO更容易,因为您可以使用日期或时间戳轻松选择变化时间步,并选择所需的最近网格点。这将是一个示例bash脚本:

# I don't know how your time axis is
# you may need to use a date with a time stamp too if your data is not e.g. daily
# see the CDO manual for how to define dates. 
date=20090101 
lat=10
lon=50

files=`ls MY_FOLDER/*.nc`
for file in $files ; do
  # select the nearest grid point and the date slice desired:
  # %??? strips the .nc from the file name
  cdo seldate,$date -remapnn,lon=$lon/lat=$lat $file ${file%???}_${lat}_${lon}_${date}.nc
done
Rscript here to read in the files

可以将所有新文件与cdo合并,但如果时间戳相同,则需要小心。您可以尝试 cdo merge cdo cat - 这样您就可以将单个文件读入R,而不必分别循环和打开每个文件。

相关问题