Roland Kofler
Roland Kofler

Reputation: 1332

How to make assertions in R?

Is it recommendable to use RUnit's check* functions to make preconditions/ postcondition statements or do this come with some penality in performance or other?

Upvotes: 12

Views: 3103

Answers (2)

I know this is an old post, but perhaps this answer will be useful to others looking for R assertions in operator form. This might be a step in the right direction if you want to tack an assertion onto the end of a troublesome statement.

"%assert%" <- function(e1, e2)
{

    args  <- as.list(match.call()[-1])
    defs  <- as.list(args$e1)
    preds <- as.list(args$e2)[-1L] 

    for(var in names(defs)[names(defs) != ""]) assign(var, eval(defs[[var]]))

    for(p   in unlist(preds)) eval(
        parse(
            text = paste0("if(!", deparse(p), ") stop('assertion ",deparse(p) , " is not true')")
        )
    )

    return(eval(args$e1))

}

Example: if you are computing the mean of a vector x and you want to make sure that each element is between one and ten you could use

mean(x = sample(1:10, size = 100, replace = T)) %assert% c(min(x) > 0 && max(x) < 11)
#5.62

If this condition isn't true, you'll get an informative(ish) error such as

mean(x = sample(11:20, size = 100, replace = T)) %assert% c(min(x) > 0, max(x) < 11)
#Error in eval(expr, envir, enclos) : assertion max(x) < 11 is not true

It's completely untested, so use at your own peril!

Upvotes: 4

Craig Schmidt
Craig Schmidt

Reputation: 660

I always use stopifnot() for assertions.

Upvotes: 28

Related Questions