To specify arguments in function created in the args
-argument of rlang::new_function
, I am looking fora way to create empty lists. These could then be fed into new_function
and return functions with predefined arguments.
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")
What I have tried so far:
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...
I suppose using unquote-splice (!!!
) is crucial keep the inputlength flexible, but I couldn't put it together with the empty lists needed for the args
-part of new_function
yet...
You can create a list the usual way with missing_arg()
in it:
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