Maharero
Maharero

Reputation: 248

R: Proper way of checking if a function has been supplied as a argument to another function

I am currently modifying a function which uses a user supplied function as one of its inputs. I tried using 'is.na' to see if a function is supplied and whilst it works - it currently also produces a warning. Is there a better way of checking that this argument exists?

 example <- function(num1, num2, functionName = NA) {

  if (is.na(functionName)) {

    return(list(num1, num2))

  } else {

    value <- functionName(num1, num2)
    return(value)

  }
}

> example(1,3)
[[1]]
[1] 1

[[2]]
[1] 3

> example(1,3, sum)
[1] 4
Warning message:
In is.na(functionName) :
  is.na() applied to non-(list or vector) of type 'builtin'

Upvotes: 1

Views: 55

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

If you are ok to pass function name as string we can use match.fun

example <- function(num1, num2, functionName = NA) {
   if (is.na(functionName)) {
     return(list(num1, num2))
   } else {
     value <- match.fun(functionName)(num1, num2)
     return(value)
   }
}

example(1, 3)

#[[1]]
#[1] 1

#[[2]]
#[1] 3

example(1,3, "sum")
#[1] 4

example(2,3, "*")
#[1] 6

Upvotes: 2

Related Questions