获取作为参数传递给R中嵌套函数的函数的名称

时间:2022-07-06 00:42:33

In R, I need the name of a function that was passed as argument to nested functions.

在R中,我需要一个作为参数传递给嵌套函数的函数的名称。

> fun1 <- function(f) deparse(substitute(f))
> fun2 <- function(f) fun1(f)
> fun1(mean)
[1] "mean"
> fun2(mean)
[1] "f"
> 

How can I obtain the name of a function independent of the number of times it has been passed as an argument to nested functions?

如何获取函数的名称,而不是它作为参数传递给嵌套函数的次数?

1 个解决方案

#1


4  

This does the substitution in the first frame on the stack:

这会在堆栈的第一帧中进行替换:

fun1 <- function(f) deparse(substitute(f, sys.frame(1)))

fun2 <- function(f) fun1(f)

fun1(mean)
#[1] "mean"
fun2(mean)
#[1] "mean"

Obviously, this will fail if you don't pass the argument through from the most outer function:

显然,如果你没有从最外层函数传递参数,这将失败:

fun3 <- function() fun2(mean)
fun3()
#[1] "f"

If will also fail, if you change the parameter name:

如果也会失败,如果更改参数名称:

fun2 <- function(g) fun1(g)
fun2(mean)
#[1] "f"

However, it might be sufficient for your use case (which you haven't described).

但是,对于您的用例(您尚未描述)可能就足够了。

If those constraints are a problem, we need something more sophisticated and inefficient:

如果这些限制是一个问题,我们需要更复杂和低效的东西:

fun1 <- function(f) {

  fr <- rev(sys.frames())

  f <- substitute(f, fr[[1]])

  #loop over the frame stack
  for (i in seq_along(fr)[-1]) {
    f <- eval(bquote(substitute(.(f), fr[[i]])))
  }

  deparse(f)
}

fun2 <- function(g) fun1(g)

fun3 <- function() fun2(mean)

fun1(mean)
#[1] "mean"
fun2(mean)
#[1] "mean"
fun3()
#[1] "mean"

Of course, this would still break in edge cases:

当然,这仍然会在边缘情况下破裂:

fun4 <- function(mean) fun3()
fun4(2)
#[1] "2"

You could try handling them, but I'll stop here.

你可以尝试处理它们,但我会停在这里。

#1


4  

This does the substitution in the first frame on the stack:

这会在堆栈的第一帧中进行替换:

fun1 <- function(f) deparse(substitute(f, sys.frame(1)))

fun2 <- function(f) fun1(f)

fun1(mean)
#[1] "mean"
fun2(mean)
#[1] "mean"

Obviously, this will fail if you don't pass the argument through from the most outer function:

显然,如果你没有从最外层函数传递参数,这将失败:

fun3 <- function() fun2(mean)
fun3()
#[1] "f"

If will also fail, if you change the parameter name:

如果也会失败,如果更改参数名称:

fun2 <- function(g) fun1(g)
fun2(mean)
#[1] "f"

However, it might be sufficient for your use case (which you haven't described).

但是,对于您的用例(您尚未描述)可能就足够了。

If those constraints are a problem, we need something more sophisticated and inefficient:

如果这些限制是一个问题,我们需要更复杂和低效的东西:

fun1 <- function(f) {

  fr <- rev(sys.frames())

  f <- substitute(f, fr[[1]])

  #loop over the frame stack
  for (i in seq_along(fr)[-1]) {
    f <- eval(bquote(substitute(.(f), fr[[i]])))
  }

  deparse(f)
}

fun2 <- function(g) fun1(g)

fun3 <- function() fun2(mean)

fun1(mean)
#[1] "mean"
fun2(mean)
#[1] "mean"
fun3()
#[1] "mean"

Of course, this would still break in edge cases:

当然,这仍然会在边缘情况下破裂:

fun4 <- function(mean) fun3()
fun4(2)
#[1] "2"

You could try handling them, but I'll stop here.

你可以尝试处理它们,但我会停在这里。