In R, one can create a function with a variable number of arguments using ...
, as illustrated here .
However, I would like to have a function with a variable number of named (formal) arguments. As a minimal example, something along the lines of
f_nargs <- function(n) {
# process argument n
# ...
f(x1, ..., xn) # What should this be ?
}
How can I achieve this?
The overall goal is to use a function(al) in a package. That function(al) requires as input a function with 3 formal arguments. While I could write the function specially for n=3, I am curious if this can be done for a general n.
Edit : Here is what I have in mind:
My current function is f(x)
, where x
is a vector of length 3.
I would like to convert this into f(x1, x2, x3)
before passing it to the functional in the package. This functional checks if length(formals(f))==3
.
Currently, I pass f
into
split_args3 <- function(f) {
force(f)
function(x1, x2, x3, ...) {
f(c(x1, x2, x3), ...)
}
}
This works, but only for a specific n. I then tried using
split_args <- function(f, d) {
force(f)
force(d)
function(...) {
dots <- list(...)
arg1 <- do.call(c, dots[1:d])
do.call(f, append(list(arg1), dots[-(1:d)]) )
}
}
but it fails the check in the functional.
Alter the list of arguments how you like, then pass it into do.call
:
split_args <- function(f, d) {
force(f)
force(d)
function(...) {
dots <- list(...)
dots <- c(list(unlist(dots[seq(d)])), dots[-seq(d)])
do.call(f, dots)
}
}
mean3 <- split_args(mean, 3)
mean3(2, NA, 3, na.rm = TRUE)
#> [1] 2.5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.