将命名参数传递给调用非变异函数的函数 [英] Pass named parameters to function that calls function that is not mutate

查看:31
本文介绍了将命名参数传递给调用非变异函数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些与 这里.

I am trying to do something very similar to here.

本质上,我需要将一个命名列表传递给一个函数,并将该命名列表作为它的参数提供给另一个函数.

Essentially, I need to pass a named list to a function, and give that named list to another function as its parameters.

如果我们点击那个链接,他们就可以通过 mutate 来实现,我可以复制它:

If we follow that link, they are able to do it with mutate, and I can replicate that:

df <- tribble(
    ~a,
    1
)

foo <- function(x, args) {
    mutate(x, !!! args)
}

foo(df, quos(b = 2, c = 3)

# A tibble: 1 x 3
      a     b     c
  <dbl> <dbl> <dbl>
1     1     2     3

但是如果我尝试用任何其他函数来做它,它就会失败.说,如果我尝试使用打印,(第一个参数是 x,所以我传递了一个带有 x 的命名列表):

But if I try to do it with any other function, it fails. Say, if I try to use print, (which the first parameter is x, so I pass a named list with x in it):

print(x= "hello")
[1] "hello"

foo <- function(x, args) {
    print(!!! args)
}

foo(df, quos(x = "hello"))

Error in !args : invalid argument type

我不确定为什么这在tidyverse"功能之外不起作用.我尝试了 sym、enquo、bang bang、curl curly 等的不同组合,但都无济于事.

I'm not sure why this won't work outside of the "tidyverse" functions. I've tried different combinations of sym, enquo, bang bang, curly curly, etc., but to no avail.

当然,我的最终目标不是使用打印,而是使用另一个用户定义的函数代替它,所以如果您对如何实现这一点有任何建议,我也将不胜感激.(顺便说一句,我必须使用命名列表,我认为我不能使用......).

Of course my final goal is not to use print but to use another user-defined-function in its place, so if you have any advice on how to achieve that, I would also greatly appreciate it. (And by the way, I do have to use a named list, I don't think I can use ...).

非常感谢您的帮助.

推荐答案

您需要 blast(),它可能会包含在 rlang 0.5.0 中.

You need blast(), which will likely be included in rlang 0.5.0.

blast <- function(expr, env = parent.frame()) {
  rlang::eval_bare(rlang::enexpr(expr), env)
}

blast(cbind(!!!letters))

这篇关于将命名参数传递给调用非变异函数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆