HappyCoding
HappyCoding

Reputation: 5139

R How to check if input is a specific function

I have a function that takes an input of a function.

 myfunc <- function(FUN){}

There, I want to check if FUN is a mean, and perform some more task

 myfunc <- function(FUN){
      ``some tasks here``
      if(FUN==mean){``some more task here``} # this FUN==mean is not valid
 }

However, it seems FUN can't be compared with this way. Is there a way to check if a specific function is inputed?

Upvotes: 1

Views: 319

Answers (1)

wibeasley
wibeasley

Reputation: 5287

Uses checkmate::assert_function() for a little extra security.

myfunc <- function(FUN){
  checkmate::assert_function(mean)

  if( identical(FUN, base::mean) ){
    return( TRUE )
  } else {
    return( FALSE )
  }
}

myfunc(mean)    # TRUE
myfunc(meanie)  # FALSE

This SO question prompts the substitute() and alternative solutions in a slightly more complicated scenario.

edit: followed @spacedman's advice and replaced substitute(FUN) == "mean" inside the 'if' condition to make it more robust (particularly against sociopaths who name their function to mask base::mean()).

Upvotes: 2

Related Questions