You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中不执行函数的前提下获取其调用的参数名称?

Solution

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

  1. Avoid executing the function: In your original example, testFun() runs the function and returns a numeric value. Instead, pass testFun (the function object) to getArgNames to skip execution entirely.

  2. formals() function: This built-in R tool retrieves a function's formal arguments as a named list. For testFun, formals(testFun) returns:

    $x
    1:20
    
    $z
    list(a = 1, b = 2)
    
  3. Extract parameter names: The names of this list are exactly the function's parameter names, so wrapping formals(value) in names() gives us the desired vector.

Edge Cases

  • Functions with no parameters: formals(function() {}) returns NULL, so getArgNames will return NULL (which is correct for a parameterless function).
  • Functions with ... (dots): For a function like function(x, ...) {}, getArgNames will return c("x", "...").
  • Primitive base functions: Some core R functions (like sum) are primitives that don't expose formals via formals(). For these, you can use args() instead: names(as.list(args(value)))[-1] (the [-1] removes the extra function( entry from the result).

内容的提问来源于stack exchange,提问作者Taz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:16:59