简体   繁体   中英

R function with strict Arguments

How to write R functions with strict arguments, meaning without getting argument as defined in definition it will fail, no matter weather that argument is used in function or not.

I had written following code where I defined input argument in definition but able to call without passing arguments

hello<- function(name){
    a<- 100
    print("welcome")
    if (a == 10){print(name)}else{print("bad")}
}
hello()

Is there ay way where I can make input argument strictly mandatory else will give error at function call

The problem is that R only throws an error for missing argument if you actually use the argument. R provides the missing(arg) function that returns TRUE if the parameter arg is missing in the function call. You can chain this with the R-equivalent of assert , which is stopifnot() .

You want to abort if missing(name) returns TRUE. So we invert the statement with the ! operator for stopifnot() , leading to the following example code:

hello<- function(name){
    stopifnot(!missing(name))

    # rest of the function:
    a<- 100
    print("welcome")
    if (a == 10){print(name)}else{print("bad")}
}

If you want the error message to be more descriptive, you can use an if-statement with stop to provide a custom error message:

hello<- function(name){  
  if (missing(name)){
    stop("YOUR CUSTOM ERROR MESSAGE HERE.")
  }
  
  # rest of the function:
  a<- 100
  print("welcome")
  if (a == 10){print(name)}else{print("bad")}
}

An alternative to missing() is defining the default value as NULL and then check is.null() at the start of the function:

hello <- function(name = NULL) {
  if (is.null(name)) stop("Argument name missing")  
  print("welcome")
  print(name)
}

force() will force the argument to be evaluated, which throws an error if it is missing.

hello <- function(name)
{
    force(name)
    # ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM