Question

If I want to see what expression was passed into a function, I can retrieve it using substitute.

f <- function(x)
{
  substitute(x)  
}

f(sin(pi))
## sin(pi)

(f returns an object of class call. substitute is usually combined with deparse to turn it into a character vector, but I don't care about that here.)

I want to repeat this with arguments in .... This attempt only returns the first argument:

g <- function(...)
{
  substitute(...)
}

g(sin(pi), cos(pi / 2))
## sin(pi)

This attempt throws an error:

h <- function(...)
{
  lapply(..., subsitute)
}

h(sin(pi), cos(pi / 2))
## Error in match.fun(FUN) :
##   'cos(pi/2)' is not a function, character or symbol

This attempt throws a different error:

i <- function(...)
{
  lapply(list(...), substitute)
}

i(sin(pi), cos(pi / 2))

## Error in lapply(list(...), substitute) : 
##   '...' used in an incorrect context

How do I retrieve the expressions that I passed into ...?

Was it helpful?

Solution

if you want to keep objetcts of class call:

i <- function(...)
{
  l <- match.call()
  l <- as.list(l)
  l <- l[-1]
  l
}

i <- function(...)
{
  l <- match.call()
  l[[1]] <- as.name("expression")
  l
}
i(sin(pi), cos(pi/2))

Or maybe you just need the match.call depending what you want to do after. hth

OTHER TIPS

Try this one:

substitute_multi <- function(...) {
   f <- function(e1, ...) {
      if (missing(e1)) return(NULL)
      else return(list(substitute(e1), substitute_multi(...)))
   }
   unlist(f(...))
}

Which gives for example:

substitute_multi(x, g(y), 1+2+3)
## [[1]]
## x
## 
## [[2]]
## g(y)
## 
## [[3]]
## 1 + 2 + 3

You may also call as.expression on the result to get an expression object.

IMHO, this solution is not as elegant as the other one, but gives some insight on how ... deals with function arguments. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top