Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tryCatch and source

Suppose I have two R files: correct.R and broken.R. What would be the best way of using tryCatch to check for errors?

Currently, I have

> 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

However, the way I've constructed the tryCatch means that I have to interrogate the x and y objects to determine if there has been an error.

Is there a better way of doing this?


The question comes from teaching. 100 students upload their R scripts and I run the scripts. To be nice, I'm planning on creating a simple function that determines if their function sources correctly. It only needs to return TRUE or FALSE.

like image 589
csgillespie Avatar asked Mar 07 '11 11:03

csgillespie


2 Answers

Try this:

> tryCatch(stop("foo"), error = function(e) {
+ cat(e$message, "\n")
+ FALSE
+ })
foo 
[1] FALSE

Alternatively, you should consider Hadley's testthat package:

> expect_that(stop("foo"), is_a("numeric"))
Error in is.vector(X) : foo
like image 51
aL3xa Avatar answered Sep 30 '22 05:09

aL3xa


To expand upon mdsumner's point, this is a simple implementation.

sources_correctly <- function(file)
{
  fn <- try(source(file))
  !inherits((fn, "try-error"))
}
like image 44
Richie Cotton Avatar answered Sep 30 '22 05:09

Richie Cotton