Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in a user defined function in R, how do i check if inputs is of the right format in R?

Tags:

arguments

r

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.

like image 257
Lost1 Avatar asked Feb 12 '23 22:02

Lost1


1 Answers

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 
like image 193
mnel Avatar answered Feb 14 '23 11:02

mnel