Marek Fiołka
Marek Fiołka

Reputation: 4949

A function passed as an argument to another function

I create a function that receives another function as an argument. How to check if such a function really exists?

It is example:

f1 = function() print("f1")

f2 = function(f){
  f()
}

f2(f1)

How to check the argument f so that f2(f3) it doesn't cause an error.

Upvotes: 2

Views: 157

Answers (2)

user2554330
user2554330

Reputation: 44867

The way to tell if it exists is to try it. Wrap it in try or tryCatch. For example,

f2 = function(f){
result <- try(f(), silent = TRUE)
if (inherits(result, "try-error"))
  message("There's something wrong with ", deparse(substitute(f)))
else
  result
}
f2(R.home)
#> [1] "/Library/Frameworks/R.framework/Resources"
f2(R.hmeo)
#> There's something wrong with R.hmeo

Created on 2021-08-22 by the reprex package (v2.0.0)

Upvotes: 3

akrun
akrun

Reputation: 887118

We may use exists i.e. invoke the function only if it exists or else don't do anything

f2 <- function(f) {
      if(exists(deparse(substitute(f)))) {
         f()
    }
}

-testing

> f2(f1)
[1] "f1"
> f2(f3)

Upvotes: 0

Related Questions