cdeterman cdeterman - 19 days ago 8
R Question

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
.

Answer

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

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

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