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