【问题标题】:R: How to get arguments of function argumentsR:如何获取函数参数的参数
【发布时间】:2017-12-21 11:41:35
【问题描述】:

假设我有一个 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 &lt;- function(x1, x2) as.list(match.call())[-1]x &lt;- function(x1, x2) lapply(as.list(match.call())[-1], as.list) `

标签: r function arguments call


【解决方案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

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

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 2020-08-22
    • 1970-01-01
    • 2019-08-23
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    相关资源
    最近更新 更多