使用tryCatch和source

csg*_*pie 7 error-handling r try-catch

假设我有两个R文件:correct.Rbroken.R.tryCatch用于检查错误的最佳方法是什么?

目前,我有

> x = tryCatch(source("broken.R"), error=function(e) e)
> x
 <simpleError in source("broken.R"): test.R:2:0: unexpected end of input
  1: x = {
     ^>
> y = tryCatch(source("correct.R"), error=function(e) e)
> y
 $value
 [1] 5

 $visible
 [1] FALSE
Run Code Online (Sandbox Code Playgroud)

但是,我构建的tryCatch方式意味着我必须询问xy对象以确定是否存在错误.

有没有更好的方法呢?


问题来自教学.100名学生上传他们的R脚本,我运行脚本.为了好,我打算创建一个简单的函数来确定它们的函数是否正确来源.它只需要返回TRUE或FALSE.

Ric*_*ton 5

为了扩展 mdsumner 的观点,这是一个简单的实现。

sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}
Run Code Online (Sandbox Code Playgroud)


Noa*_*oah 2

也许我没有考虑到这一点,但由于您只是在寻找布尔值,因此您可以测试以下内容是否存在$visible

y <- tryCatch(source("broken.R"), error=function(e) e)
works <- !is.null(y$visible) #y$visible would be null if there were an error
Run Code Online (Sandbox Code Playgroud)

这能解决您正在寻找的问题吗?您可以将其包装在循环中(或使用 lapply),例如:

for(i in 1:length(students)) {
  works[i] <- !is.null(tryCatch(source(student_submissions[i]), error=function(e) e)$visible)
}
Run Code Online (Sandbox Code Playgroud)