[R] Extracting a (*specific*) variable name from a list of function arguments (not "...")

Marc Schwartz marc_schwartz at me.com
Sun Jan 30 18:01:57 CET 2011


On Jan 30, 2011, at 10:38 AM, Tal Galili wrote:

> Hello all,
> 
> I would like to extract the variable name passed into a specific argument of
> a function.
> Using match.call() will give me a list of arguments and what was passed into
> them, but I couldn't find how to get a particular argument out of it (at
> least without using some string manipulation).
> 
> Here is an example (in it, my objective is to know what is the variable name
> assigned to the argument "b"):
> 
> foo <- function(a, b, c)
> {
> print(match.call())
> }
> x = 1 ; y = 1
> foo(x, y)  # here the answer should be "y"
> foo(c= x, y)  # here the answer should be "" (or NULL/NA)
> 
> 
> Any suggestion on how to do this?
> 
> 
> BTW, the purpose of this is to be able to avoid the error produced by, for
> example, this:
> 
> yy <- data.frame(y = 1:10, x = 1:10)
> plot(y, data = yy) # error
> plot(y~x, data = yy) # no error...


Tal,

Try this:

x <- 1
y <- 1

foo <- function(a, b, c) {as.list(match.call())}


> foo(x, y)
[[1]]
foo

$a
x

$b
y


> foo(x, y)$b
y


> foo(c = x, y)$b
NULL



If you really only want 'b' and not be able to get the other arguments, you can use:

foo2 <- function(a, b, c) {as.list(match.call())$b}

> foo2(x, y)
y

> foo2(c = x, y)
NULL


In your plot example above, you are first dispatching plot.default(), which of course has no 'data' argument. In the second case, you are dispatching plot.formula() which does have a 'data' argument, as do most, if not all, R functions that take a formula as an argument.

HTH,

Marc Schwartz



More information about the R-help mailing list