If my function has input (x,y,z)
in R, I want to write a line of code which ensures data for x
is of the right form.
i.e. x
is just a real number rather than anything else such as a vector or a list. I assume the code would go something like
if ( ... ){stop("x must be a real number")}
I would like to know what goes inside of the bracket instead of ...
?
The reason is that if I write in a vector, the programme just take the first component of the vector as the input. R would give a warning about this, but I would like the programme to be stopped immediately.
If you want to "stop" if your argument is of length 1, and a real number
You could use stopifnot
foo <- function(x, y, z) {
stopifnot(length(x)==1L & is.numeric(x))
}
or perhaps
foo <- function(x, y, z){
if(!(length(x)==1L & is.numeric(x))) { stop("x must be a real number")}
}
stop
allows you to specify the error message whereas stopifnot
will return the condition that was tested. (Both have advantages)
The benefit of stopifnot
is that it can tell you exactly which of multiple conditions failed.for example (noting that I am now feeding multiple expressions)
foo <- function(x, y, z) {
stopifnot(length(x)==1L , is.numeric(x))
}
foo('a')
# Error: is.numeric(x) is not TRUE
foo(c(1,2))
# Error: length(x) == 1L is not TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With