【发布时间】:2019-02-26 16:50:56
【问题描述】:
要在rlang::new_function 的args-参数中创建的函数中指定参数,我正在寻找一种创建空 列表的方法。然后可以将这些输入new_function 并返回带有预定义参数的函数。
library(rlang)
create_empty_list <- function(arg_names_chr) {
# input lenght should be variable, so probably !!! should be used
}
create_empty_list(arg_names_chr = c("arg1", "arg2"))
#> NULL
# desired output
args_specified <- exprs(arg1=, arg2=)
args_specified
#> $arg1
#>
#>
#> $arg2
# use with new_function()
new_function(
args_specified,
expr(print("hello world")),
caller_env()
)
#> function (arg1, arg2)
#> print("hello world")
到目前为止我所尝试的:
c("arg1", "arg2") %>%
map(parse_expr) %>%
exprs(!!!arg_names_chr, .named = TRUE)
#> $arg1
#> arg1
#>
#> $arg2
#> arg2
#>
#> # the contents of the list should be empty though...
我想使用 unquote-splice (!!!) 是保持输入长度灵活的关键,但我无法将它与 new_function 的 args 部分所需的空列表放在一起......
【问题讨论】:
-
顺便说一下,不要使用
base::parse()或rlang::parse_expr()创建符号。更喜欢base::as.symbol()或rlang::sym(),它们更健壮。它们总是创建一个符号,而如果名称中有特殊字符,则解析可能会以各种方式失败。