Home > Back-end >  Null value transformed in function call
Null value transformed in function call

Time:04-01

I encountered some strange behaviour that I don't quite understand. I often set non-required parameters as NULL in a function, so that I can check them using is(!missing).

However, when I have one function pass a NULL value to another function, the NULL value gets interpreted as non-NULL:

fun1 <- function(value=NULL){
  if (missing(value)) stop("\n[!] Must provide a value. Exiting.")
  cat("Value is missing: ", missing(value), "value: ", value, "\n")
}

wrapper <- function(value=NULL){
  ret <- fun1(value=value)
  cat(ret)
}

wrapper(value = "Here")
# -> Value is missing:  FALSE value:  Here

# I expected this to print "Value is missing:  TRUE"
wrapper(value = NULL)
# -> Value is missing:  FALSE value:

Can anyone shed some light on this (and how I can fix the problem)?

CodePudding user response:

The missing argument does not actually evaluate for null values, but checks if a value was specified as an argument to a function.

Below, missing isn't checking the value of x, but it is checking to see if x was provided as an argument to is_missing.

is_missing <- function(x=NULL) {
  missing(x)
}

is_missing()
#> [1] TRUE

is_missing(x = NULL)
#> [1] FALSE

I'm not sure what your desired function might look like, but here's an example of a potential refactor:

fun1 <- function(value = NULL) {
  if(is.null(value)) {
    miss <- TRUE
    print(paste0("value is missing: ", miss))
  } else {
    miss <- FALSE
    print(paste0("value is missing: ", miss, ". value = ", value))
  }
}

fun1(value = NULL)
#> [1] "value is missing: TRUE"
fun1()
#> [1] "value is missing: TRUE"
fun1(value = "X")
#> [1] "value is missing: FALSE. value = X"
  •  Tags:  
  • r
  • Related