在for循环中跳过错误

时间:2013-02-07 10:14:06

标签: r for-loop

我正在做一个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的帖子,但没有一个对我有用(或者至少我无法正确应用这个功能)。帮助文件也不是很有帮助。

帮助将不胜感激。感谢。

3 个答案:

答案 0 :(得分:96)

一种(脏)方法是使用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 !

但是你可以将你的指令包装到tryCatch中,并使用一个不起作用的错误处理函数,例如:

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

编辑:因此,在您的案例中应用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")})
}

答案 1 :(得分:3)

如果错误发生(例如,如果中断是唯一的),则不可能首先在myplotfunction()函数之前或之前进行测试而不是捕获错误,并且仅针对那些情况绘制它不会出现?!

答案 2 :(得分:0)

这是一种简单的方法

for (i in 1:10) {

  skip_to_next <- FALSE

  # Note that print(b) fails since b doesn't exist

  tryCatch(print(b), error = function(e) { skip_to_next <- TRUE})

  if(skip_to_next) { next }     
}

请注意,即使有错误,循环也会完成所有10次迭代。您显然可以将print(b)替换为所需的任何代码。如果{

中包含多行代码,也可以在}tryCatch中包装多行代码