R中的空文件的错误/异常处理

时间:2014-07-05 07:49:13

标签: r exception exception-handling error-handling try-catch

我在两天前第一次在python中听说过异常处理,因此我想在这里申请R.我在堆栈溢出或其他一些在线Q& As中查看了一些问题但是我是仍然真的很困惑使用它。

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

例如,我有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.
    > 

1 个答案:

答案 0 :(得分: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)