【问题标题】:passing formula in a list to `rlang::exec`将列表中的公式传递给`rlang::exec`
【发布时间】:2021-01-05 18:26:38
【问题描述】:

我正在尝试在自定义函数中使用rlang::exec,我想将其他参数作为列表传递,然后将它们拼接起来。通常这可以正常工作。但是当涉及formula 参数时,我在执行此例程时遇到了问题。

没有列表

library(rlang)

exec(
  .fn = stats::t.test,
  formula = wt ~ am,
  data = mtcars
)
#> 
#>  Welch Two Sample t-test
#> 
#> data:  wt by am
#> t = 5.4939, df = 29.234, p-value = 6.272e-06
#> alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
#> 95 percent confidence interval:
#>  0.8525632 1.8632262
#> sample estimates:
#> mean in group 0 mean in group 1 
#>        3.768895        2.411000

带列表


extra.args <- list(formula = wt ~ am) 

exec(
  .fn = stats::t.test,
  data = mtcars,
  !!!extra.args
)
#> Error in t.test.default(data = structure(list(mpg = c(21, 21, 22.8, 21.4, : argument "x" is missing, with no default

我怎样才能让它工作?

【问题讨论】:

    标签: r rlang tidyeval


    【解决方案1】:

    我不确定这是rlang::exec 的错。问题确实与 S3 调度以及基于第一个参数的类而不是参数名称调用不同函数的事实有关。使用您当前的调用方法,您将在公式之前传递data=。这在直接调用函数的时候也会出现问题

    stats::t.test(data=mtcars, formula=wt~am)
    

    解决此问题的最简单方法是以“自然”顺序传递参数,以便进行正确的 S3 调度

    extra.args <- list(formula = wt ~ am) 
    exec(
      .fn = stats::t.test,
      !!!extra.args,
      data = mtcars
    )
    

    或不命名公式参数,使其成为第一个未命名参数。

    extra.args <- list(wt ~ am) 
    
    exec(
      .fn = stats::t.test,
      data = mtcars,
      !!!extra.args
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      相关资源
      最近更新 更多