使用 R,我试图打开单个文件夹(例如 20 个文件)中的所有 netcdf 文件,读取单个变量,并创建一个结合所有文件值的单个 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))
Run Code Online (Sandbox Code Playgroud)
其中 414 和 315 是我想要提取的值的经度和纬度,240 是时间步数。
我找到了这个线程,它解释了如何打开多个文件。在此之后,我设法使用以下方法打开文件:
filenames= list.files('/MY_FOLDER/',pattern='*.nc',full.names=TRUE)
ldf = lapply(filenames,open.nc)
Run Code Online (Sandbox Code Playgroud)
但现在我被困住了。我试过
var1= lapply(ldf, var.get.nc(ldf,'LWdown',start=c(414,315,1),count=c(1,1,240)))
Run Code Online (Sandbox Code Playgroud)
但它不起作用。增加的复杂性是每个 nc 文件都有不同数量的时间步长。所以我有两个问题:
1:如何打开所有文件,读取每个文件中的变量并将所有值合并到一个数据框中?2:如何将最后一个维度设置count为所有文件都不同?
以下@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
}
Run Code Online (Sandbox Code Playgroud)
可能有更优雅的方式,但它有效。
| 归档时间: |
|
| 查看次数: |
7710 次 |
| 最近记录: |