1

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?

HappyCoding
  • 5,029
  • 7
  • 31
  • 51

1 Answers1

2

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()).

wibeasley
  • 5,000
  • 3
  • 34
  • 62
  • This works if any function *named* `mean` is passed. This might not be the base R function `mean`. To compare with the base R function `mean()` use `identical(FUN, base::mean)` – Spacedman Jun 25 '18 at 07:21
  • @Spacedman, I didn't consider that. It's updated to reflect your improvement. – wibeasley Jun 25 '18 at 07:30