首页 > 解决方案 > 如何在R中获取闭包的参数数量

问题描述

我在变量中有函数:

foo <- function(a, b) {}

我可以用:

body(foo)

对于函数的源代码,我可以使用这个:

length(substitute(function(a, b) {})[[2]])

但前提是我将函数内联。那么如何获取函数的参数数量呢?

我也试过

length(foo)
# 1

所以这不起作用。我想编写可以与可以具有 1 个或 2 个参数的处理程序一起使用的函数,所以我已经编写了通用实用程序:

#' Function call function fn with the only arguments it accept
invoke <- function(fn, ...) {
  if (!is.function(fn)) {
    stop("invoke: argument need to be a function")
  }
  count <- length(substitute(fn)[[2]])
  do.call(fn, list(...)[1:count])
}

还是更好的方法?我有这样的功能:

fn1 <- function(a, b) {

}
fn2 <- function() {

}

我想调用他们两个,而不会对未使用的参数有错误

invoke(fn1, 10, 20)
invoke(fn2, 10, 20)

第二个应该忽略这两个论点。

标签: rfunctionintrospection

解决方案


推荐阅读