【问题标题】:Get function components of function call inside a function获取函数内部函数调用的函数组件
【发布时间】:2020-12-03 11:15:31
【问题描述】:

是否可以检索函数调用的函数组件?也就是说,是否可以在另一个函数调用中使用as.list(match.call())

背景是,我想要一个函数,它接受函数调用并返回所述函数调用的组件。

get_formals <- function(x) {
  # something here, which would behave as if x would be a function that returns
  # as.list(match.call())
}

get_formals(mean(1:10))
# expected to get:
# [[1]]
# mean
#
# $x
# 1:10

预期结果是 get_formals 返回,因为在提供的函数调用中调用了 match.call()

mean2 <- function(...) {
  as.list(match.call())
}
mean2(x = 1:10)
# [[1]]
# mean2
# 
# $x
# 1:10

另一个例子

这个问题背后的动机是检查memoised 函数是否已经包含缓存值。 memoise 有函数has_cache() 但需要以特定方式调用has_cache(foo)(vals),例如,

library(memoise)

foo <- function(x) mean(x)
foo_cached <- memoise(foo)

foo_cached(1:10) # not yet cached
foo_cached(1:10) # cached

has_cache(foo_cached)(1:10) # TRUE
has_cache(foo_cached)(1:3) # FALSE

我的目标是记录函数调用是否被缓存。

cache_wrapper <- function(f_call) {
  is_cached <- has_cache()() # INSERT SOLUTION HERE
  # I need to deconstruct the function call to pass it to has_cache
  # basically
  # has_cache(substitute(expr)[[1L]])(substitute(expr)[[2L]]) 
  # but names etc do not get passed correctly

  if (is_cached) print("Using Cache") else print("New Evaluation of f_call")
  f_call
}

cache_wrapper(foo_cached(1:10))
#> [1] "Using Cache"     # From the log-functionality
#> 5.5                   # The result from the function-call

【问题讨论】:

  • 我假设 get_formals = function (expr) substitute(expr)[[2L]] 不足以满足您的目的?
  • 你要处理多少层环境?我不确定您是想要 Konrad 的方法还是需要更古怪的方法。您的“函数调用”来自哪里,例如一些deparse 操作?如果您可以发布一个演示,说明您将如何使用此检索工具,那将很有帮助。
  • @KonradRudolph 的解决方案差不多了,但我放弃了参数的名称。
  • 我只处理一层。我将在上面的代码中添加另一个示例。

标签: r metaprogramming


【解决方案1】:

您可以使用match.call() 进行参数匹配。

get_formals <- function(expr) {
  call <- substitute(expr)
  call_matched <- match.call(eval(call[[1L]]), call)
  as.list(call_matched)
}

get_formals(mean(1:10))

# [[1]]
# mean
# 
# $x
# 1:10

library(ggplot2)
get_formals(ggplot(mtcars, aes(x = mpg, y = hp)))

# [[1]]
# ggplot
# 
# $data
# mtcars
# 
# $mapping
# aes(x = mpg, y = hp)

library(dplyr)
get_formals(iris %>% select(Species))

# [[1]]
# `%>%`
# 
# $lhs
# iris
# 
# $rhs
# select(Species)

编辑: 感谢@KonradRudolph 的建议!

上面的函数找到了right函数。它将在get_formals() 的父级范围内搜索,而不是在调用者的范围内。更安全的方法是:

get_formals <- function(expr) {
  call <- substitute(expr)
  call_matched <- match.call(eval.parent(bquote(match.fun(.(call[[1L]])))), call)
  as.list(call_matched)
}

match.fun() 对于正确解析被同名非函数对象遮蔽的函数很重要。例如,如果mean 被向量覆盖

mean <- 1:5

get_formals()的第一个例子会报错,而更新的版本运行良好。

【讨论】:

  • 注意这会找到 right 函数:它将在 get_formals 的父级范围内搜索,而不是在调用者的范围内。您可以通过将eval 替换为eval.parent(bquote(match.fun(.(call[[1L]])))) 来解决此问题(这非常少,但match.fun 对于正确解析被同名的非函数对象遮蔽的函数很重要)。
  • @KonradRudolph 感谢您的详细建议。已更新。
【解决方案2】:

如果您没有提供所有参数,这是一种方法,它也可以从函数中获取默认值:

get_formals <- function(call)
{
  f_list <- as.list(match.call()$call)
  func_name <- f_list[[1]]
  p_list <- formals(eval(func_name))
  f_list <- f_list[-1]
  ss <- na.omit(match(names(p_list), names(f_list)))
  if(length(ss) > 0) {
    p_list[na.omit(match(names(f_list), names(p_list)))] <- f_list[ss]
    f_list <- f_list[-ss]
  }
  unnamed <- which(!nzchar(sapply(p_list, as.character)))
  if(length(unnamed) > 0)
  {
    i <- 1
    while(length(f_list) > 0)
    {
      p_list[[unnamed[i]]] <- f_list[[1]]
      f_list <- f_list[-1]
      i <- i + 1
    }
  }
  c(func_name, p_list)
}

这给出了:

get_formals(rnorm(1))
[[1]]
rnorm

$n
[1] 1

$mean
[1] 0

$sd
[1] 1
get_formals(ggplot2::ggplot())
[[1]]
ggplot2::ggplot

$data
NULL

$mapping
aes()

$...


$environment
parent.frame()

要让它在一个层面上发挥作用,您可以执行以下操作:

foo <- function(f_call) {
  eval(as.call(list(get_formals, call = match.call()$f_call)))
}

foo(mean(1:10))
[[1]]
mean

$x
1:10

$...

【讨论】:

  • 这让我快到了。你知道如何在一级使用这个功能吗?即foo &lt;- function(f_call) return(get_formals(f_call))?
  • 太棒了!这样做!我已经为您的函数实现了 Konrad 的 eval.parent 调用。将发布更新以显示对我有用的完整解决方案!
【解决方案3】:

这个答案主要基于Allens answer,但实现了关于evaleval.parent 函数的Konrads 评论。 此外,一些do.call 被抛出以最终确定上面示例中的cache_wrapper

library(memoise)

foo <- function(x) mean(x)
foo_cached <- memoise(foo)

foo_cached(1:10) # not yet cached
#> [1] 5.5
foo_cached(1:10) # cached
#> [1] 5.5

has_cache(foo_cached)(1:10)
#> [1] TRUE
has_cache(foo_cached)(1:3)
#> [1] FALSE

# As answered by Allen with Konrads comment
get_formals <- function(call) {
  f_list <- as.list(match.call()$call)
  func_name <- f_list[[1]]
  # changed eval to eval.parent as suggested by Konrad...
  p_list <- formals(eval.parent(eval.parent(bquote(match.fun(.(func_name))))))
  f_list <- f_list[-1]
  ss <- na.omit(match(names(p_list), names(f_list)))
  if(length(ss) > 0) {
    p_list[na.omit(match(names(f_list), names(p_list)))] <- f_list[ss]
    f_list <- f_list[-ss]
  }
  unnamed <- which(!nzchar(sapply(p_list, as.character)))
  if(length(unnamed) > 0) {
    i <- 1
    while(length(f_list) > 0) {
      p_list[[unnamed[i]]] <- f_list[[1]]
      f_list <- f_list[-1]
      i <- i + 1
    }
  }
  c(func_name, p_list)
}

# check if the function works with has_cache
fmls <- get_formals(foo_cached(x = 1:10))
do.call(has_cache(eval(parse(text = fmls[1]))),
        fmls[2])
#> [1] TRUE


# implement a small wrapper around has_cache that reports if its using cache
cache_wrapper <- function(f_call) {
  fmls <- eval(as.call(list(get_formals, call = match.call()$f_call)))
  is_cached <- do.call(has_cache(eval(parse(text = fmls[1]))),
                       fmls[2])
  if (is_cached) print("Using Cache") else print("New Evaluation of f_call")
  f_call
}

cache_wrapper(foo_cached(x = 1:10))
#> [1] "Using Cache"
#> [1] 5.5

cache_wrapper(foo_cached(x = 1:30))
#> [1] "New Evaluation of f_call"
#> [1] 5.5

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 2012-01-12
    • 2017-03-05
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多