sfcheung
sfcheung

Reputation: 478

Check the name of a function passed as an argument in an R function

Suppose I wrote a function that accept another function as an argument:

fct1 <- function(FUN) {
    # If FUN is rnorm, then do this.
    # If FUN is rbeta, then do this.
  }

How should I check whether FUN is rnorm?

I know I can do this to convert the function to a list by as.list() and then coerce it to a string by toString():

toString(as.list(rnorm))

The result is:

", 0, 1, .Call(C_rnorm, n, mean, sd)"

I can then check the content for C_rnorm.

But I think this is not a good solution. I also read somewhere (I cannot remember the source) that coercing a closure to a list and then a string is possible just for backward compatibility, and is not encouraged.

I also thought about body(). For example,

body(rnorm)

The result is:

.Call(C_rnorm, n, mean, sd)

However, then how can I check if C_rnorm is inside the call? I tried to use as.list() and then toString():

toString(as.list(body(rnorm)))

This is the result:

".Call, C_rnorm, n, mean, sd"

However, is this a good practice?

Upvotes: 1

Views: 111

Answers (1)

Molx
Molx

Reputation: 6931

You can use match.call:

fct1 <- function(FUN) {
  called <- match.call()$FUN
  if(called == "rnorm") {
    return("Passed rnorm")
  } else {
    return("Not rnorm")
  }

}

fct1(rnorm)
# [1] "Passed rnorm"
fct1(rlnorm)
# [1] "Not rnorm"

Upvotes: 2

Related Questions