R: find the original name of the function passed as an argument

I have functions f1

and f2

that take a function as an argument, for example:

f1 <- function(FUN) {
    ...
}


f2 <- function(FUN)  {
   f1(FUN=FUN)
}

      

From within the function, f1

I need to find the original name of the function passed to f2

, for example "myFunc"

, but not "FUN"

.

Basically, we can imagine a function f1

to f2(f1(mean))

return "mean"

? If it FUN

is anonymous, we can, for example, return NULL

or NA

.

Is there a simple / standard way to do this in R? I tried to manually find the identical function code using (but it's not very clean and I'm looking for a better solution)

fn = unlist(as.list(lsf.str(envir=.GlobalEnv)))
for (f in fn) {
    if (setequal(paste(body(myFunc)),paste(body(f)))) { 
      return(f)
    }
}

      

+3


source to share


2 answers


You can also use the package lazyeval

:

f1 <- function(FUN) {
  lazyeval::expr_text(FUN)
}


f2 <- function(FUN)  {
  f1(FUN = FUN)
}

f2(f2(f2(mean)))
[1] "f2(f2(mean))"

      


This worked for me:

f1 <- function(FUN) {
  eval(quote(substitute(FUN)), envir = parent.frame())
}


f2 <- function(FUN)  {
  f1(FUN=FUN)
}

f2(mean)

      



In this case f1

, the call is evaluated substitute(FUN)

in the f2 environment.

See the results:

> f2(mean)
mean
> f2(function(x) {NULL})
function(x) {
  NULL
}

      

If you want the output to be a string you need to use deparse

then f1 can be defined:

f1 <- function(FUN) {
  eval(quote(deparse(substitute(FUN))), envir = parent.frame())
}

      

0


source


In most cases, the following function gives the original name.

find.original.name <- function(fun) {
    objects <- ls(envir = environment(fun))
    for (i in objects) {
        if (identical(fun, get(i, envir = environment(fun)))) {
            return(i)
        }
    }
}

a <- ls
find.original.name(a)
# [1] ls

a <- glm
find.original.name(a)
# [1] "glm"

a <- function() print("test")
find.original.name(a)
# [1] "a"

      



But if a copy of a function (more precisely, it is not a copy), and the original function is in the same environment, this function may not work correctly ...

test <- function() print("test")
a <- test
find.original.name(a)
# [1] "a"

      

0


source







All Articles