I need to capture the prespecified arguments of a function call. This seems easy for the unspecified ones via rlang::list2(...)
, but more difficult for the specified ones ("specified" meaning defined in the formals of the function).
I have experimented with base::match.call
and the functions from https://rlang.r-lib.org/reference/index.html#section-calls, but haven't yet been successful.
library(rlang)
capture_dots <- function(..., arg1) {
list2(...)
}
capture_dots("abc", arg1 = 1, arg2 = 2)
#> [[1]]
#> [1] "abc"
#>
#> $arg2
#> [1] 2
capture_prespecified("abc", arg1 = 1, arg2 = 2)
#> $arg1
#> [1] 1
If you want to capture all the named parameter to your function, you can use formals()
to get their names (and just filter out the "...")
capture_dots <- function(..., arg1) {
args <- Filter(function(x) x!="...", names(formals()))
as.list(environment())[args]
}
capture_dots("abc", arg1 = 1, arg2 = 2)
Or, if you run it early in the function, the dots wont expand and there won't be any other variables so you can just grab the current environment with
capture_dots <- function(..., arg1) {
as.list(environment())
}