使用RnetCDF打开和读取多个netcdf文件 [英] Opening and reading multiple netcdf files with RnetCDF

查看:357
本文介绍了使用RnetCDF打开和读取多个netcdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using R, I am trying to open all the netcdf files I have in a single folder (e.g 20 files) read a single variable, and create a single data.frame combining the values from all files. I have been using RnetCDF to read netcdf files. For a single file, I read the variable with the following commands:

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是时间步数.

where 414 & 315 are the longitude and latitude of the value I would like to extract and 240 is the number of timesteps.

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

I have found this thread which explains how to open multiple files. Following it, I have managed to open the files using:

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

但是现在我被卡住了.我尝试过

but now I'm stuck. I tried

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

但是它不起作用. 更为复杂的是,每个nc文件都有不同数量的时间步长.所以我有2个问题:

but it doesn't work. The added complication is that every nc file has a different number of timestep. So I have 2 questions:

1:如何打开所有文件,读取每个文件中的变量并将所有值组合在一个数据框中? 2:如何设置count中的最后一个尺寸以针对所有文件而有所不同?

1: How can I open all files, read the variable in each file and combine all values in a single data frame? 2: How can I set the last dimension in count to vary for all files?

推荐答案

@mdsummer的注释之后,我尝试执行do循环,并设法完成了我需要做的所有事情:

Following @mdsummer's comment, I have tried a do loop instead and have managed to do everything I needed:

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

也许有一种更优雅的方法,但是它可行.

There may be a more elegant way but it works.

这篇关于使用RnetCDF打开和读取多个netcdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆