Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass optional arguments to function, three dots

I'm confused how ... works.

tt = function(...) {
  return(x)
}

Why doesn't tt(x = 2) return 2?

Instead it fails with the error:

Error in tt(x = 2) : object 'x' not found

Even though I'm passing x as argument ?

like image 522
Rafael Avatar asked May 24 '18 13:05

Rafael


People also ask

What does the 3 dots mean in Java?

The "Three Dots" in java is called the Variable Arguments or varargs. It allows the method to accept zero or multiple arguments. Varargs are very helpful if you don't know how many arguments you will have to pass in the method.

How do I use three dots over it in R?

If you have used R before, then you surely have come across the three dots, e.g. 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.

How do you add an optional argument to a function?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

What is the dot dot dot argument in R?

... argument is a special argument useful for passing an unknown number of arguments to another function. This is widely used in R, especially in generic functions such as. plot()


1 Answers

Because everything you pass in the ... stays in the .... Variables you pass that aren't explicitly captured by a parameter are not expanded into the local environment. The ... should be used for values your current function doesn't need to interact with at all, but some later function does need to use do they can be easily passed along inside the .... It's meant for a scenario like

ss <- function(x) {
   x
}

tt <- function(...) {
  return(ss(...))
}

tt(x=2)

If your function needs the variable x to be defined, it should be a parameter

tt <- function(x, ...) {
  return(x)
}

If you really want to expand the dots into the current environment (and I strongly suggest that you do not), you can do something like

tt <- function(...) {
  list2env(list(...), environment())
  return(x)
}
like image 151
MrFlick Avatar answered Nov 02 '22 23:11

MrFlick