Erik Iverson
2010-Jul-02 20:01 UTC
[R] generating list of all arguments that function was called with
Hello, Consider: f1 <- function(a, b, c, d, ...) { c(list(a = a, b = b, c = c, d = d), list(...)) } > f1(a = 1, b = 2, c = 3, d = 4, more = 5) $a [1] 1 $b [1] 2 $c [1] 3 $d [1] 4 $more [1] 5 Question: I'm guessing there exists a function such that I don't have to list each bound argument separately in the list in 'f1'. It seems like it should be easy but it's escaping me. Thanks, Erik
Marc Schwartz
2010-Jul-02 20:37 UTC
[R] generating list of all arguments that function was called with
On Jul 2, 2010, at 3:01 PM, Erik Iverson wrote:> Hello, > > Consider: > > f1 <- function(a, b, c, d, ...) { > c(list(a = a, b = b, c = c, d = d), list(...)) > } > > > f1(a = 1, b = 2, c = 3, d = 4, more = 5) > $a > [1] 1 > > $b > [1] 2 > > $c > [1] 3 > > $d > [1] 4 > > $more > [1] 5 > > > Question: I'm guessing there exists a function such that I don't have to list each bound argument separately in the list in 'f1'. It seems like it should be easy but it's escaping me. > > Thanks, > ErikErik, Use ?match.call as follows: MyFunc <- function(a, b, c, d, ...) { as.list(match.call(expand.dots = TRUE)[-1]) }> MyFunc(a = 10, c = 8)$a [1] 10 $c [1] 8> MyFunc(a = 10, b = 5, y = 6)$a [1] 10 $b [1] 5 $y [1] 6 The [-1] in the call removes the first element, which will be the function name (eg. 'MyFunc'). The returned object from match.call() will be a language object, which can be coerced to a list, yielding the argument names and values. 'expand.dots' is used to deal with the '...' args, if they exist. HTH, Marc Schwartz