Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better error message for stopifnot?

Tags:

r

I am using stopifnot and I understand it just returns the first value that was not TRUE. I f that is some freaky dynamic expression someone who is not into the custom function cannot really make something out of that. So I would love to add a custom error message. Any suggestions?

Error: length(unique(nchar(check))) == 1 is not TRUE

Basically states that the elements of the vector check do not have the same length. Is there a way of saying: Error: Elements of your input vector do not have the same length!?

like image 701
Matt Bannert Avatar asked Dec 01 '11 15:12

Matt Bannert


4 Answers

Use stop and an if statement:

if(length(unique(nchar(check))) != 1) 
  stop("Error: Elements of your input vector do not have the same length!")

Just remember that stopifnot has the convenience of stating the negative, so your condition in the if needs to be the negation of your stop condition.


This is what the error message looks like:

> check = c("x", "xx", "xxx")
> if(length(unique(nchar(check))) != 1) 
+   stop("Error: Elements of your input vector do not have the same length!")

Error in eval(expr, envir, enclos) : 
  Error: Elements of your input vector do not have the same length!
like image 108
Andrie Avatar answered Nov 18 '22 07:11

Andrie


A custom message can be added as a label to your expression:

stopifnot("Elements of your input vector do not have the same length!" =
  length(unique(nchar(check))) == 1)

# Error: Elements of your input vector do not have the same length!
like image 36
Brian Montgomery Avatar answered Nov 18 '22 07:11

Brian Montgomery


The assertive and assertthat packages have more readable check functions.

library(assertthat)
assert_that(length(unique(nchar(check))) == 1)
## Error: length(unique(nchar(check))) == 1 are not all true.

library(assertive)
assert_is_scalar(unique(nchar(check)))
## Error: unique(nchar(check)) does not have length one.

if(!is_scalar(unique(nchar(check)))) 
{
  stop("Elements of check have different numbers of characters.")
}
## Error: Elements of check have different numbers of characters.
like image 14
Richie Cotton Avatar answered Nov 18 '22 07:11

Richie Cotton


Or you could package it up.

assert <- function (expr, error) {
  if (! expr) stop(error, call. = FALSE)
}

So you have:

> check = c("x", "xx", "xxx")
> assert(length(unique(nchar(check))) == 1, "Elements of your input vector do not have the same length!")

Error: Elements of your input vector do not have the same length!
like image 7
Max Gasner Avatar answered Nov 18 '22 05:11

Max Gasner