获取函数内部函数调用的函数组件

如何解决获取函数内部函数调用的函数组件

是否可以检索函数调用的函数组件?也就是说,是否可以在另一个函数调用上使用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

另一个例子

此问题背后的动机是检查memoise d函数是否已包含缓​​存的值。 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

解决方法

您可以使用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()的第一个示例将出错,而更新后的版本运行良好。

,

如果您不提供所有参数,这是一种从函数中获取默认值的方法:

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

$...
,

此答案主要基于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),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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-