Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any arguments were passed via "..." (ellipsis) in R? Is missing(...) valid?

Tags:

r

ellipsis

I'd like to check whether an R function's "..." (ellipsis) parameter has been fed with some values/arguments.

Currently I'm using something like:

test1 <- function(...) {
   if (missing(...)) TRUE
   else FALSE
}

test1()
## [1] TRUE
test1(something)
## [2] FALSE

It works, but ?missing doesn't indicate if that way is proper/valid.

If the above is not correct, what is THE way to do so? Or maybe there are other, faster ways? PS. I need this kind of verification for this issue.

like image 213
gagolews Avatar asked Oct 31 '14 22:10

gagolews


People also ask

What does 3 dots mean in R?

If you have any basic experience with R, you probably noticed that R uses three dots ellipsis (…) to allow functions to take arguments that weren't pre-defined or hard-coded when the function was built.

What does dot dot dot do in R?

(dot-dot-dot) Functions can have a special argument ... (pronounced dot-dot-dot). With it, a function can take any number of additional arguments. In other programming languages, this type of argument is often called varargs (short for variable arguments), and a function that uses it is said to be variadic.

How do you find an argument in a function in R?

args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.


2 Answers

Here's an alternative that will throw an error if you try to pass in a non-existent object.

test2 <- function(...) if(length(list(...))) FALSE else TRUE

test2()
#[1] TRUE
test2(something)
#Error in test2(something) : object 'something' not found
test2(1)
#[1] FALSE
like image 57
GSee Avatar answered Sep 28 '22 06:09

GSee


I think match.call is what you need:

test <- function(...) {match.call(expand.dots = FALSE)}

> test()
test()

> test(x=3,y=2,z=5)
test(... = list(x = 3, y = 2, z = 5))

It will give you every time the values passed in the ellipsis, or it will be blank if you won't pass any.

Hope that helps!

like image 39
LyzandeR Avatar answered Sep 28 '22 08:09

LyzandeR