1

使用 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 是时间步数。

我发现这个线程解释了如何打开多个文件。在它之后,我设法使用以下方法打开文件:

 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为所有文件的变化?

4

3 回答 3

5

@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
}

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

于 2013-10-29T11:35:12.593 回答
1

您错误地传递了附加的函数参数。你应该使用...它。这是一个如何传递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))

虽然这是未经测试的。

于 2013-10-29T10:16:52.363 回答
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 mergecdo cat - 这样您就可以将单个文件读入 R,而不必分别循环和打开每个文件。

于 2017-04-28T13:35:13.487 回答