Getting a function name as a string

Viewed 37281

Say I have a bunch of functions, each with something likeMyFunction.1, etc. I want to pass these functions into another function, which prints out a small report. Ideally I'd like to be able to label sections of a report by which function is being used to generate the results.

So are there any nice ways of getting the name of a predefined function as a string?

9 Answers

Nice observation by @nfultz, so the answer to this thread's question would be :-

workingFunction <- Function(f)
{ functionName <- as.character(substitute(f)) }

Or

workingFunction <- Function(f)
{ functionName <- deparse(substitute(f)) }

All the other answers would simply return the parameter name itself ('f' in the example above) - I tried them all since I've been working on a function and experienced this issue of not being able to retrieve a function's name inside another function wherein the first is passed as parameter to the second function while calling it. Hope my answer helps to all those who might be stuck for the same!

I also struggled a lot with this issue and unfortunately the given solutions were not working out for me, but I came up with a way to get the name with R6 classes.

Here a minimal example:

NameProvider <-
  R6::R6Class(
    "NameProvider",
    base::list(
      get_fun_name = function(fun_name) { return(fun_name)})
    )

NameUser <-
  R6::R6Class(
    "NameUser",
    base::list(
      do_something = function(fun)
        {
          np <- NameProvider$new()
          fname <- np$get_fun_name(fun_name = base::as.character(base::substitute(fun)))
          do_the_thing <- paste0("THIS IS ", base::toupper(fname), "!!!")
          return(do_the_thing)
        }
        )
      )

nu <- NameUser$new()
nu$do_something(fun = mean) 

The class NameProvider just returns the name as a string and in the class NameUser the call for base::as.character(base::substitute(...)) is made.

Related