Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand an ellipsis (...) argument without evaluating it in R

I need a function that accepts an arbitrary number of arguments and stores them in a variable as an expression without evaluating them. I managed to do it with match.call but it seems a little "kludgy".

foo <- function(...) {
  expr <- match.call()
  expr[[1]] <- expression
  expr <- eval(expr)
  # do some stuff with expr
  return(expr)
}

> bla
Error: object 'bla' not found
> foo(x=bla, y=2)
expression(x = bla, y = 2)

Clarification

To clarify, I'm asking how to write a function that behaves like expression(). I can't use expression() directly for reasons that are too long to explain.

like image 875
Ernest A Avatar asked Nov 13 '12 00:11

Ernest A


People also ask

What is an ellipsis in R?

If you have used R before, then you surely have come across the three dots, e.g. print(x, ...) print (x, ...) print (x, ...) In technical language, this is called an ellipsis. And it means that the function is designed to take any number of named or unnamed arguments. By the way, the ellipsis is not a specialty of R.

Can I use the ellipsis with other regular arguments in Python?

As an example, try running this piece of code with both options: Some tend to think that it’s not possible to use the ellipsis with other regular arguments. This is not the case, and the ellipsis-arguments shouldn’t be the only ones in your function.

What is the use of ellipsis in JavaScript?

The … operator, technically known as the ellipsis, allows a function to take arguments that are not predefined in its definition. The ellipsis is useful when we don’t know how many arguments a function may take.

How to use arguments in R?

To start working with R arguments you must have a clear understanding of functions in R We can pass an argument to a function when we call that function. We just need to give the value of the argument inside the parenthesis after the function’s name. The following is the example of a function with a single argument.


3 Answers

The most idiomatic way is:

f <- function(x, y, ...) {
  match.call(expand.dots = FALSE)$`...`
}
like image 125
hadley Avatar answered Jan 01 '23 19:01

hadley


Using . from plyr as a prototype

foo <-   function (...) 
  {
  as.expression(as.list(match.call()[-1]))
  }
like image 35
mnel Avatar answered Jan 01 '23 21:01

mnel


The ultimate intended outcome is slightly vague (could you clarify a bit?). However, this may be helpful:

foo2 <- function(...) {
  expr <- as.list(substitute(list(...)))[-1L]
  class(expr) <- "expression"
  expr
}

example:

foo2(x=bla, y=2)
# expression(x = bla, y = 2)
like image 27
Ricardo Saporta Avatar answered Jan 01 '23 19:01

Ricardo Saporta