rlang:从可变字符输入创建空列表
rlang: Creating empty lists from variable character input
要在 rlang::new_function
的 args
参数中创建的函数中指定参数,我正在寻找创建 空 列表的方法。然后可以将这些输入到带有预定义参数的 new_function
和 return 函数中。
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 (!!!
) 是保持输入长度灵活的关键,但我无法将它与 args
部分所需的空列表放在一起 new_function
还...
您可以按照通常的方式创建一个列表,其中包含 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
要在 rlang::new_function
的 args
参数中创建的函数中指定参数,我正在寻找创建 空 列表的方法。然后可以将这些输入到带有预定义参数的 new_function
和 return 函数中。
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 (!!!
) 是保持输入长度灵活的关键,但我无法将它与 args
部分所需的空列表放在一起 new_function
还...
您可以按照通常的方式创建一个列表,其中包含 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