循环nc open函数的问题

时间:2017-08-16 11:10:46

标签: r netcdf

我正在尝试循环

ncin_old<-nc_open("filename", write=TRUE, readunlim=TRUE, verbose=FALSE, 
           auto_GMT=TRUE, suppress_dimvals=FALSE )

这样的功能

library(ncdf.tools)
library(ncdf4)
library(ncdf4.helpers)
library(RNetCDF)
library(abind)
setwd("D:/Rwork/Project")   # set working folder

# This is the directory where the file for analysing are
dir("D:/Rwork/Project/MASTER_FILES")-> xlab 
filelist <- paste("MASTER_FILES/", dir("MASTER_FILES"), sep="") 

N <- length(filelist)     # Loop over the individual files
for(j in 1:N) { 
  ncin_old <- nc_open("filelist[j]", write=TRUE, readunlim=TRUE, verbose=FALSE, 
           auto_GMT=TRUE, suppress_dimvals=FALSE )
}

但是我收到了这个错误

  

nc_open出错(&#34; filelist [j]&#34;,write = TRUE,readunlim = TRUE,   verbose = FALSE,:nc_open尝试打开文件时出错   文件列表[j]的

如果我在filelist[j]之后删除了循环中的lat文件打开的所有内容 但是nc_open(x, write)似乎并不喜欢被循环播放。

2 个答案:

答案 0 :(得分:0)

我已修复了一些您的代码问题,如下所示。我认为现在是正确的。

library(ncdf4)
# set the folder with the files
setwd("D:/Rwork/Project/MASTER_FILES")

# you need the files path, not the directory path
# list only the files with the .nc extension
filelist <- list.files(pattern = "\\.nc$")

# Loop over the individual files
# The filelist cannot be between quotation marks as in your code
N <- length(filelist)
for(j in 1:N) { 
  ncin_old <- nc_open(filelist[j], write=TRUE, readunlim=TRUE, verbose=FALSE, 
           auto_GMT=TRUE, suppress_dimvals=FALSE)
}

答案 1 :(得分:0)

我用过lapply:

library(ncdf4)
# set the folder that contains all the files
setwd("C:/...")

# create a list with the files with the .nc extension
filelist <- list.files(pattern = "*.nc")
filelist # It contains all the files .nc

# To open all files: Loop over the individual files
for (i in 1:length(filelist)) { 
     all_nc_files <- lapply(filelist, nc_open)
} 

运行该命令,我将获得“ all_nc_files”,其中包含所有打开的.nc文件,现在我可以使用它们。 希望它能起作用!