2014-07-05 30 views
0

两天前我听说python中的第一次异常处理,因此我想在R中应用这里。我查看了一些在堆栈溢出中发布的问题或一些其他的在线Q &因为,但我仍然很困惑在使用它。R中的空文件的错误/异常处理

如果有人可以用这个简单的例子回答它,我会很感激,所以稍后我可以将它应用于我的问题。

例如,我有3个数据文件,文件名如下所示;而第一个文件是一个0字节的空文件。我能做些什么来继续运行所有文件的循环,并且从空文件中提取的数字可以表示为NA?

> output_names_hdf5_list[1:5] 
    [1] "simulation-results fL=0.1,fks=1,fno=0.1,fnc=0.1,fr=0.1,fs=0.1.hdf5" 
    [2] "simulation-results fL=0.1,fks=1,fno=0.1,fnc=0.1,fr=0.1,fs=1.05.hdf5" 
    [3] "simulation-results fL=0.1,fks=1,fno=0.1,fnc=0.1,fr=0.1,fs=2.hdf5"  

    for (i in 1:5){ 
     channelflow_outlet[,i]=h5read(paste(outputdir, output_names_hdf5_list[i], sep=""),"Channel")$Qc_out[460,][2:100] 
    } 

随着try功能我可以管理,而不停留在一个错误消息,运行程序,但是当我用channelflow_outlet[,i]= h5read(....)更换内部try功能argunment,它只返回错误。

for (i in 1:5){ 
     try(h5read(paste(outputdir, output_names_hdf5_list[i], sep=""),"Channel")$Qc_out[460,][2:100]) 
    } 

没有错误处理,它会有这样的错误信息。

> h5read(paste(outputdir, output_names_hdf5_list[1], sep=""),"Channel")$Qc_out[460,][2:100] 
    HDF5: unable to open file 
    Error in h5checktypeOrOpenLoc(file, readonly = TRUE) : 
     Error in h5checktypeOrOpenLoc(). File 'D:/Data/Mleonard/pytopkapi.staged.makefile/RunModel/Output/3x6-729-04072014/simulation-results fL=0.1,fks=1,fno=0.1,fnc=0.1,fr=0.1,fs=0.1.hdf5' is not a valid HDF5 file. 
    > 
+0

请参阅'?tryCatch'中的示例。您可以在错误或动态警告中指定行为。 –

+0

@ Roman,我尝试过使用'tryCatch()'并重写'h5read()'读取文件的一部分作为函数,但它仍然不起作用。结果全部以NA返回。 –

回答

1

我希望我的代码有帮助。对于代码中的这些消息,如果需要,可以将其删除。他们纯粹是为了帮助你看到它显示警告或错误的地方。

setwd("D:/Dropbox/Test/"); outputdir = "D:/Dropbox/Test/" 

    output_names_hdf5_list=c("simulation-results fL=0.1,fks=1,fno=1.05,fnc=1.05,fr=1.05,fs=1.05.hdf5", 
      "simulation-results fL=0.1,fks=1,fno=1.05,fnc=2,fr=1.05,fs=1.05.hdf5", 
      "simulation-results fL=0.1,fks=1,fno=2,fnc=1.05,fr=0.1,fs=1.05.hdf5", 
      "simulation-results fL=0.1,fks=1,fno=2,fnc=1.05,fr=2,fs=2.hdf5", 
      "simulation-results fL=0.5,fks=1,fno=2,fnc=2,fr=0.1,fs=1.05.hdf5") 

    channelflow_outlet = matrix(NA, nrow=100, ncol=5) 

    hdf5_list_reading_tool= function(output_names_hdf5_list) { 
    out = tryCatch(
     { 
      message("This is the 'try' part") 
      h5read(paste(outputdir, output_names_hdf5_list, sep=""),"Channel")$Qc_out[460,][2:100] 
     }, 
     error=function(cond) { 
      message("Here's the original error message:") 
      message(cond) 
      return(rep(NA,100)) 
     }, 
     warning=function(cond) { 
      message("Here's the original warning message:") 
      message(cond) 
      return(rep(NA,100)) 
     }, 
     finally={ 
      message(paste("Processed URL:", output_names_hdf5_list)) 
      message("Some other message at the end") 
     } 
    ) 
    return(out) 
    } 

    channelflow_outlet=sapply(output_names_hdf5_list, hdf5_list_reading_tool)