首页 文章

在for循环中跳过错误

提问于
浏览
44

我正在做一个for循环,为我的6000 X 180矩阵生成180个图形(每列1个图形),一些数据不符合我的标准,我得到错误:

"Error in cut.default(x, breaks = bigbreak, include.lowest = T) 
'breaks' are not unique".

我对错误很好,我希望程序继续运行for循环,并给我一个列出了这个错误的列(作为包含列名的变量可能?) .

这是我的命令:

for (v in 2:180){
    mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
    pdf(file=mypath)
    mytitle = paste("anything")
    myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
    dev.off()
}

注意:我发现了很多关于tryCatch的帖子,但没有一个对我有效(或者至少我无法正确应用这个功能) . 帮助文件也不是很有帮助 .

帮助将不胜感激 . 谢谢 .

2 回答

  • 3

    一种(脏)方法是使用带有空函数的 tryCatch 进行错误处理 . 例如,以下代码引发错误并中断循环:

    for (i in 1:10) {
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
    }
    
    [1] 1
    [1] 2
    [1] 3
    [1] 4
    [1] 5
    [1] 6
    [1] 7
    Erreur : Urgh, the iphone is in the blender !
    

    但是你可以将你的指令包装到带有错误处理函数的_1007862中,该函数不执行任何操作,例如:

    for (i in 1:10) {
      tryCatch({
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
      }, error=function(e){})
    }
    
    [1] 1
    [1] 2
    [1] 3
    [1] 4
    [1] 5
    [1] 6
    [1] 7
    [1] 8
    [1] 9
    [1] 10
    

    但我认为至少应该打印错误消息,以便在让代码继续运行时知道是否发生了错误:

    for (i in 1:10) {
      tryCatch({
        print(i)
        if (i==7) stop("Urgh, the iphone is in the blender !")
      }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
    }
    
    [1] 1
    [1] 2
    [1] 3
    [1] 4
    [1] 5
    [1] 6
    [1] 7
    ERROR : Urgh, the iphone is in the blender ! 
    [1] 8
    [1] 9
    [1] 10
    

    EDIT : 因此,在您的情况下应用 tryCatch 将是这样的:

    for (v in 2:180){
        tryCatch({
            mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
            pdf(file=mypath)
            mytitle = paste("anything")
            myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
            dev.off()
        }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
    }
    
  • 82

    如果错误发生(例如,如果中断是唯一的),则不可能首先在 myplotfunction() 函数之前或之前进行测试,而只能在不出现错误的情况下绘制它?

相关问题