如何在R中不执行函数的前提下获取其调用的参数名称?
To get the parameter names of a function without executing it, you need to pass the function object itself (not the result of calling it) to your helper function. Here's how to implement getArgNames:
testFun <- function(x = 1:20, z = list(a = 1, b = 2)) x %>% sin %>% sum getArgNames <- function(value) { # Prevent accidental passing of function results instead of the function itself if (!is.function(value)) { stop("Input must be a function object, not the output of calling it!") } # Extract parameter names from the function's formal arguments names(formals(value)) } # Correct usage: pass the function directly, not testFun() arg.names <- getArgNames(testFun) arg.names # Output: [1] "x" "z"
Explanation
Avoid executing the function: In your original example,
testFun()runs the function and returns a numeric value. Instead, passtestFun(the function object) togetArgNamesto skip execution entirely.formals()function: This built-in R tool retrieves a function's formal arguments as a named list. FortestFun,formals(testFun)returns:$x 1:20 $z list(a = 1, b = 2)Extract parameter names: The names of this list are exactly the function's parameter names, so wrapping
formals(value)innames()gives us the desired vector.
Edge Cases
- Functions with no parameters:
formals(function() {})returnsNULL, sogetArgNameswill returnNULL(which is correct for a parameterless function). - Functions with
...(dots): For a function likefunction(x, ...) {},getArgNameswill returnc("x", "..."). - Primitive base functions: Some core R functions (like
sum) are primitives that don't expose formals viaformals(). For these, you can useargs()instead:names(as.list(args(value)))[-1](the[-1]removes the extrafunction(entry from the result).
内容的提问来源于stack exchange,提问作者Taz

