R:如何获取函数参数的参数

R: How to get arguments of function arguments

假设我有一个 function 需要另外两个 functions 和一些 arguments 作为 arguments:

a <- function(x, y = 2){
  x + y
}

b <- function(b1, b2 = 7){
  b1 + b2
}

x <- function(x1, x2){
  # Get arguments of arguments
}

有没有办法从 x() 参数中获取 arguments 的列表?这是,通话后:

x(a(3,4), b(5))

我想要这样的列表:

$x1
$x1$x
[1] 3

$x1$y
[1] 4


$x2
$x2$b1
[1] 5

$x2$b2
[1] 7
x <- function(x1, x2){

  theCall <- lapply(as.list(match.call()),as.list)[-1]


  args <- lapply(theCall, function(x) as.list(formals(as.character(x))))

  Map(function(a, b) {
    b <- b[-1]

    for (i in seq_along(a)) {
      if(i <= length(b)) a[i] <- b[i]
    }
    a
  }, args, theCall)
}

str(x(a(3,4), b(5)))
#List of 2
# $ x1:List of 2
#  ..$ x: num 3
#  ..$ y: num 4
# $ x2:List of 2
#  ..$ b1: num 5
#  ..$ b2: num 7

显然,即使使用有效的函数调用也可以轻松破解:

str(x(a(3,4), b(,b1 = 5)))
#List of 2
# $ x1:List of 2
#  ..$ x: num 3
#  ..$ y: num 4
# $ x2:List of 2
#  ..$ b1: symbol 
#  ..$ b2: num 5

让这个函数对所有可能的输入都正确,留作 reader 的练习。