cdeterman
cdeterman

Reputation: 19960

R - Converting a Function to String

I am working on a function that would behave similar to Reduce where you pass in a function and dispatch it over the arguments. Here is simple example to demonstrate what I am working on.

fun <- function(f){

    switch(f,
           `+` = "addition",
           stop("undefined")
    )
}

fun(`+`)

Now this clearly won't work as it stands because switch requires a character or numeric EXPR. What I don't know how to do is convert the function f that is passed to fun to a string.

Upvotes: 1

Views: 76

Answers (2)

jdobres
jdobres

Reputation: 11957

Going off of Pierre's comment above, one can use identical to test whether two functions are the same. This doesn't work well with switch, but an if/else tree is still relatively simple:

fun <- function(f) {
    if (identical(f, `+`)) {
        return('addition')
    } else if (identical(f, mean)) {
        return('mean')
    } else {
        return('undefined')
    }
}

Upvotes: -1

Pierre L
Pierre L

Reputation: 28441

One approach is to capture the input and deparse the call.

fun <- function(f){
  switch(deparse(substitute(f)),
         `+` = "addition",
         stop("undefined")
  )
}

fun(`+`)
#[1] "addition"

Upvotes: 4

Related Questions