打印在for循环中引发错误的列表项,并继续下一个列表项 [英] Print list item that throws error in for loop, and continue with next list item
问题描述
我正在尝试使长列表中的哪个文件引发错误更加清晰。我试过将 for
循环包装在 tryCatch()
中,但是我无法获得寻找。我要寻找的结果是:如果文件 i
抛出错误 sprintf(错误:%s出现格式问题,i)
。
I'm trying to add some clarity to which file in a long list is throwing an error. I've tried wrapping the for
loop in tryCatch()
, but I can't get the behavior I'm looking for. The result I'm going for is: if file i
throws an error sprintf("Error: %s has a formatting problem", i)
.
下面,我们创建一个包含三个文件的目录,其中两个文件应该由正确地读入列表, c >循环,这将引发错误,因为它是
xlsx
文件。
Below, we create a directory with three files, two of which should be read correctly into a list by the for
loop, one which will throw an error because it's a xlsx
file.
请注意,以下代码将创建并删除目录和三个文件
dir.create("Demo999")
setwd("Demo999")
write.csv(mtcars,"mtcars.csv")
xlsx::write.xlsx(mtcars,"mtcars.xlsx")
write.csv(mtcars,"mtcars2.csv")
files <- list.files()
data <- list()
for (i in files){
f <- read.csv(i)
data[[i]] <- f
}
# clean up generated files
setwd("..")
unlink("Demo999", recursive= TRUE, force= TRUE)
我想要的输出是:
错误:mtcars.xlsx出现格式问题。
"Error: mtcars.xlsx has a formatting problem."
此代码无法运行,但是 tryCatch
块的示例:
This code does not run, but is a sample tryCatch
block:
tryCatch({
for (i in files){
f <- read.csv(i)
data[[i]] <- f
}
}, error = function() sprintf("Error: %s has a formatting problem", i))
推荐答案
将 tryCatch
放入循环内,而不是在循环之外。您不想尝试整个循环,如果循环失败,请执行其他操作;您希望循环尝试每个列表元素,并在失败时显示错误。这样,您可以返回并仅尝试重新尝试失败的文件。尝试以下操作:
Put the tryCatch
inside the loop, not outside the loop. You don't want try the whole loop, and do something else if the loop fails; you want the loop to try each list element, and print an error if it fails. This way you can go back and re-attempt only the failed files. Try this:
for (i in files){
tryCatch({
f <- read.csv(i)
data[[i]] <- f
},
error = function(e) print(sprintf("Error: %s has a formatting problem", i))
)
}
# [1] "Error: mtcars.xlsx has a formatting problem"
names(data)
# [1] "mtcars.csv" "mtcars2.csv"
请注意,在此示例中,您知道名称(数据)
成功的原因,因此您可以轻松找到失败= setdiff(文件,名称(数据))
。
Note that, in this nice example, you know what succeeded from the names(data)
, so you can easily find fails = setdiff(files, names(data))
.
这篇关于打印在for循环中引发错误的列表项,并继续下一个列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!