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 ?
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.
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.
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.
... 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()
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)
}
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