在 for 循环中跳过错误

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

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

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 的帖子,但是没有一个对我有用(或者至少我不能正确地应用这个函数)。帮助文件也帮不上什么忙。

我会很感激你的帮助的,谢谢。

185705 次浏览

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 !

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

Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction() function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!

Here's a simple way

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 }
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch