Home > Back-end >  How to test if else conditions with functions as input?
How to test if else conditions with functions as input?

Time:01-08

I have an R function that takes another function as an input (e.g. mean, var, etc.). I would like to return a different result if the input function is "variance" instead of mean etc. Something like an equals assignment statement for functions. Note that the function input should be the function itself as an as.function() class object, rather than a string "function".

myFun = function(...,FUN) {
  ...
  if (FUN!=var) {...} else {...}
}

The above does not work in its current form. I obtain the following error:

Error in FUN != var : 
  comparison (2) is possible only for atomic and list types

CodePudding user response:

Using ensym

myFun <- function(FUN)
  {
  if(rlang::as_string(rlang::ensym(FUN)) != "var") {
      print("fx isn't var")
  } else {
    print("fx is var")
  }
}

-testing

> myFun(var)
[1] "fx is var"
> myFun(mean)
[1] "fx isn't var"

Although, the function can be passed directly

 f1 <- function(x, FUN) FUN(x)
> f1(1:5, var)
[1] 2.5
> f1(1:5, mean)
[1] 3

CodePudding user response:

You can convert the function name to character and do your test on that:

myFun = function(FUN) {
  if (as.character(substitute(FUN)) != "var") {
    print("fx isn't var")
  } else {
    print("fx is var")
  }
}

myFun(var)
# [1] "fx is var"

myFun(mean)
# [1] "fx isn't var"

Note this will also print "fx is var" if you pass "var" rather than var, and will print "fx isn’t var" even if the input isn’t a function at all. You could add stopifnot(is.function(FUN)) to the beginning of your function to handle these cases.

  • Related