Checking a function input is supplied in R

Go To StackoverFlow.com

3

I have the following (pointless) function, in R:

say <- function (string){
  if(!exists("string")){
    stop("no output string was specified")
  }
  cat(string)
}

Which is all very well at checking the string object actually exists. However, if an object of the same name is already floating about in the workspace, it'll ignore the error even though that's not defined in the function.

Can I make it so the exists() function only looks in the function-space for the object?

2012-04-05 22:19
by dplanet


5

You're looking for missing. Others do something like this instead:

say <- function(string=NULL){
  if(is.null(string)){
    stop("no output string was specified")
  }
  cat(string)
}
2012-04-05 22:22
by Joshua Ulrich
i.e. if(missing(string)) stop()jbaums 2012-04-05 23:15
what are the advantages of is.null versus missing - Xu Wang 2012-04-06 04:34
@Xu: it is possible to have a variable in existence whose value is NULL, so it depends on exactly what you want to do with the variable, basically - Carl Witthoft 2012-04-06 11:19
Edit: IIRC @jbaums' construct fails if you write function(string=NULL), so use function(string) , i.e. no default value - Carl Witthoft 2012-04-06 11:25
@CarlWitthoft ok, thanks for the explanation - Xu Wang 2012-04-06 22:40
Ads