在for循环中跳过错误

Err*_*404 53 for-loop r

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

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

我对错误很好,我希望程序继续运行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()
}
Run Code Online (Sandbox Code Playgroud)

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

帮助将不胜感激.谢谢.

jub*_*uba 109

一种(脏)方法是使用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 !
Run Code Online (Sandbox Code Playgroud)

但是你可以将你的指令包装成一个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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

编辑:所以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")})
}
Run Code Online (Sandbox Code Playgroud)

  • 只要代码或数据中出现错误,`tryCatch`指令就应该"拦截"错误...... (2认同)
  • 不,你不明白`tryCatch`是如何工作的.请参阅我编辑的答案,了解您可以在代码中使用它的方法(显然未经过测试).但Daniel Fischer的回答可能是最好的:你应该真正尝试理解错误是什么,并在你的功能中处理它. (2认同)

use*_*745 7

这是一个简单的方法

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 }     
}
Run Code Online (Sandbox Code Playgroud)

请注意,尽管有错误,循环仍会完成所有 10 次迭代。您显然可以print(b)用您想要的任何代码替换。您还可以包装多行代码{}如果您有不止一行代码tryCatch