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)
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.
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.
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.
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.
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.
The most idiomatic way is:
f <- function(x, y, ...) {
match.call(expand.dots = FALSE)$`...`
}
Using .
from plyr
as a prototype
foo <- function (...)
{
as.expression(as.list(match.call()[-1]))
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With