Nightwriter
Nightwriter

Reputation: 524

get ... inside R functions

in R you can pass on parameters in functions using "...", e.g.

myfun <- function(..., cex=0.7, mytext=1:10){
plot(...)
text(...,label=mytext)
}

Is there a way to get the values of "..." inside the function? Suppose you do

myfun(runif(10), runif(10), cex=0.3, label=1:10)

You will get an error because cex is set twice in text(), so nice to extract x and y from "..." for use in text(). (I know par("usr") can be used for getting x and y from the plotting device).

Upvotes: 3

Views: 86

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545598

There are different ways:

The simplest method is to use

dots = list(...)

which returns a named list of the arguments. However, this evaluates all arguments and although this is usually what you want, sometimes it isn’t. To get an unevaluated list of the arguments, use

dots = match.call(expand.dots = FALSE)$...

To illustrate the difference, consider

f = function (...) list(...)
g = function (...) match.call(expand.dots = FALSE)$...

Called as

f(2 + 2)
g(2 + 2)

Results in:

[[1]]
4

[[1]]
2 + 2

Upvotes: 7

Related Questions