Maju116
Maju116

Reputation: 1607

R: How to get arguments of function arguments

Let's say I've got a function that takes another two functions with some arguments as arguments:

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

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

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

Is there a way to get a list of arguments from x() arguments ? This is, after call:

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

I would like to get list like:

$x1
$x1$x
[1] 3

$x1$y
[1] 4


$x2
$x2$b1
[1] 5

$x2$b2
[1] 7

Upvotes: 1

Views: 76

Answers (1)

Roland
Roland

Reputation: 132576

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

Obviously, this can be broken easily even with valid function calls:

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

Making this function correct for all possible input is left as an exercise for the reader.

Upvotes: 1

Related Questions