101

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

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

帮助将不胜感激。谢谢。

4

3 回答 3

175

一种(肮脏的)方法是使用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")})
}
于 2013-02-07T11:02:42.157 回答
11

这是一个简单的方法

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

于 2019-12-24T01:07:44.713 回答
3

myplotfunction() 如果错误会发生(即如果中断是唯一的)并且只为那些不会出现的情况绘制它,是否可以先在函数中或之前测试,而不是捕获错误?!

于 2013-02-07T11:13:20.107 回答