本文介绍了在 for 循环中跳过错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am doing a for loop for generating 180 graphs for my 6000 X 180 matrix (1 graph per column), some of the data don't fit my criteria and i get the error:

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

我对错误没问题,我希望程序继续运行 for 循环,并给我一个列表,列出导致此错误的列(可能作为包含列名的变量?).

I am fine with the error, I want the program to continue running the for loop, and give me a list of what columns made this error (as a variable containing column names maybe?).

这是我的命令:

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

Note: I have found numerous posts about tryCatch and none of them worked for me (or at least i couldn't apply the function correctly). The help file wasn't very helpful as well.

帮助将不胜感激.谢谢.

Help would be appreciated. Thanks.

推荐答案

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

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

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 带有一个什么都不做的错误处理函数,例如:

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

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

但我认为您至少应该打印错误消息以了解在让代码继续运行的同时是否发生了不好的事情:

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

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), "
")})
}

[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 应该是这样的:

EDIT : So to apply tryCatch in your case would be something like :

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), "
")})
}

这篇关于在 for 循环中跳过错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 21:22