View source: R/12_FilterArgs4Func.R
| FilterArgs4Func | R Documentation |
FilterArgs4Func filters a list of arguments to include only those that
match the formal arguments of a specified function, with optional support
for preserving additional arguments via the keep parameter.
This is useful for preparing argument lists for function calls, especially
when dealing with functions that have many optional parameters or when
passing arguments through multiple function layers.
FilterArgs4Func(args_list, fun, keep = NULL)
args_list |
A named list of arguments to filter |
fun |
The target function whose formal arguments will be used for filtering |
keep |
Character vector of argument names to preserve regardless of
whether they appear in |
This function is particularly useful in scenarios where you have a large
list of parameters and want to pass only the relevant ones to a specific
function while preserving certain arguments for downstream processing
(e.g., arguments consumed by nested ... parameters).
The keep parameter enables flexible argument forwarding patterns
common in wrapper functions and pipeline designs.
A filtered list containing:
Arguments from args_list that match formal parameters of fun
(excluding the "..." parameter)
Additional arguments specified in keep (if not NULL)
formals() for accessing function formal arguments,
do.call() for executing functions with argument lists,
names() for working with list names
## Not run:
# Example function with specific parameters
example_function <- function(a, b, c = 10, d = 20) {
return(a + b + c + d)
}
# Create a list with both relevant and irrelevant arguments
all_args <- list(
a = 1,
b = 2,
c = 3,
e = 4, # Not in function formals
f = 5 # Not in function formals
)
# Basic usage: filter to only include arguments matching function parameters
filtered_args <- FilterArgs4Func(all_args, example_function)
print(filtered_args)
#> $a
#> [1] 1
#>
#> $b
#> [1] 2
#>
#> $c
#> [1] 3
# Advanced usage: preserve additional arguments for downstream processing
filtered_with_keep <- FilterArgs4Func(all_args, example_function, keep = c("e", "f"))
print(filtered_with_keep)
#> $a
#> [1] 1
#>
#> $b
#> [1] 2
#>
#> $c
#> [1] 3
#>
#> $e
#> [1] 4
#>
#> $f
#> [1] 5
# Execute with filtered arguments
result <- do.call(example_function, filtered_args)
print(result)
#> [1] 16
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.