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

问题描述 投票:1回答:1

假设我有一个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
}

有没有办法从arguments论证中获取x()列表?这是在通话后:

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

我想获得如下列表:

$x1
$x1$x
[1] 3

$x1$y
[1] 4


$x2
$x2$b1
[1] 5

$x2$b2
[1] 7
r function arguments call
1个回答
1
投票
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

使所有可能的输入正确的这个功能留给读者练习。

© www.soinside.com 2019 - 2024. All rights reserved.