【问题标题】:rlang: Creating empty lists from variable character inputrlang:从可变字符输入创建空列表
【发布时间】:2019-02-26 16:50:56
【问题描述】:

要在rlang::new_functionargs-参数中创建的函数中指定参数,我正在寻找一种创建 列表的方法。然后可以将这些输入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_functionargs 部分所需的空列表放在一起......

【问题讨论】:

  • 顺便说一下,不要使用base::parse()rlang::parse_expr() 创建符号。更喜欢base::as.symbol()rlang::sym(),它们更健壮。它们总是创建一个符号,而如果名称中有特殊字符,则解析可能会以各种方式失败。

标签: r rlang tidyeval


【解决方案1】:

您可以按照通常的方式创建一个列表,其中包含missing_arg()

arg_names <- c("arg1", "arg2")

args <- rep(list(missing_arg()), length(arg_names))
names(args) <- arg_names

new_function(args, NULL)
#> function (arg1, arg2)
#> NULL

【讨论】:

  • 其他创建缺失参数的方法:base::quote(expr = ), rlang::expr(), ...
猜你喜欢
  • 2015-05-08
  • 2021-10-05
  • 2017-05-18
  • 2021-11-26
  • 1970-01-01
  • 2012-07-24
  • 2014-02-10
  • 2020-06-26
  • 2011-04-20
相关资源
最近更新 更多