Saren Tasciyan
Saren Tasciyan

Reputation: 483

How to get function name, when substitute returns an expression

I am using Shiny selectInput, where functions' names are matched with match.fun and passed to another function. e.g. One can choose between mean, median, sum etc. and passed like this: someFunction(summary.fun = match.fun(input$summary_fun))

When I try to recover the name of the function within the function with substitute(summary.fun), which returns match.fun(input$summary_fun).

I can pass this function to other functions such as aggregate(..., FUN = summary.fun), and everything works fine.

I would like to retrieve the function name as "mean", "median", "sum" etc.

Upvotes: 1

Views: 106

Answers (1)

r2evans
r2evans

Reputation: 160447

You can't in that way, not easily. From ?match.fun:

Value: A function matching 'FUN'...

To me this means it returns the function itself, not a label or name or pointer to that function.

To increase the likelihood that you can get a usable "character function name" as well as the actual function body, try

someFunction <- function(summary.fun, ...) {
  if (is.character(summary.fun)) {
    funcname <- summary.fun
    realfunc <- match.fun(summary.fun)
  } else if (is.function(summary.fun)) {
    funcname <- deparse(substitute(summary.fun))
    realfunc <- summary.fun
  }
  # ...
}
quux <- reactive({
  req(try(match.fun(input$summary_fun)))
  someFunction(summary.fun = input$summary_fun, ...)
})

The use of req(try(match.fun(input$summary_fun))) means that the reactive block will not fire if the input$summary_fun does not match a known function name. (It may not be completely necessary in your context, over to you.) (The use of try is because req triggers "not-truthy" on an object of class '"try-error"' (from ?req), which will happen if input$summary_fun does not reflect a known function.)

Upvotes: 2

Related Questions