将不同函数的参数传递给R函数

时间:2019-07-17 12:31:33

标签: r rlang

我有一个“主”功能foo,需要从中调用另外两个功能fun1fun2。这些每个都有单独的参数集,我想从外面设置。

library(tidyverse)
#> Registered S3 methods overwritten by 'ggplot2':
#>   method         from 
#>   [.quosures     rlang
#>   c.quosures     rlang
#>   print.quosures rlang

fun1 <- function(a, c) {
  print(glue::glue("a is {a}"))
  print(glue::glue("c is {c}"))
}

fun2 <- function(e, g) {
  print(glue::glue("e is {e}"))
  print(glue::glue("g is {g}"))
}

foo <- function(something, additional_args) {
  print(glue::glue("Called with {something}"))
  # I know I can do this, but I don't want to explicitly specify a, c, e and g here!)
  fun1(additional_args$fun1_args$a, additional_args$fun1_args$c)
  fun2(additional_args$fun2_args$e, additional_args$fun2_args$g)
}

foo("something", additional_args = list(
  fun1_args = list(a = "b", c = "d"),
  fun2_args = list(e = "f", g = "h")
))
#> Called with something
#> a is b
#> b is d
#> c is f
#> d is h

reprex package(v0.3.0)于2019-07-17创建

很明显,我不得不在foo中重复参数的名称并不是很好。函数fun1fun2可能需要更多的参数,也可能不是全部,或者有一些默认值。

我认为我没有完全掌握准引用。我通读了the documentation,但没有任何内容适用。我不想在任何地方使用...,因为我不想混淆函数fun1fun2的参数。

如何替换这些奇怪的调用(在其中我明确指定了参数),以便它们仅转发参数?

  fun1(additional_args$fun1_args$a, additional_args$fun1_args$c)
  fun2(additional_args$fun2_args$e, additional_args$fun2_args$g)

我尝试过

  fun1_args = enquos(additional_args$fun1_args)
  fun1(!!! fun1_args)

但是它说:

  

错误:要捕获的输入必须是参数名称

我也尝试过fun1(!!!additional_args$fun1_args),但是它说:

  

!additional_args $ fun1_args中的错误:参数类型无效

0 个答案:

没有答案