I want to wrap a replicate()
call in a function, using the ellipsis. Say:
fo()
has 2 arguments: fo <- function(x, times) x * times
replicate()
will pass the first by name, the second using the ...
.
rep_it <- function(N, ...) replicate(N, fo(x=3, ...))
It turns out, instead of passing the second argument, replicate seems to be passing 0 values?
fo <- function(x, times) x * times
rep_it <- function(N, ...) replicate(N, fo(x=3, ...))
rep_it(5, times = 4) # should return 5 times 3 * 4 = 12
#> [1] 0 0 0 0 0
This seems to be due to the ellipsis! If I were to name the argument, that would be fine:
rep_it2 <- function(N, times) replicate(N, fo(x=3, times))
rep_it2(5, times = 4)
#> [1] 12 12 12 12 12
Why is this happening, and how to handle it? I see that there is a quite complicated call inside the replicate()
function: eval.parent(substitute(function(...) expr))
, but I don't really understand what is happening there...
Thanks!
We capture the ...
and pass it in replicate
fo <- function(x, times) x * times
rep_it <- function(N, ...) {
args <- unlist(list(...), use.names = FALSE)
replicate(N, fo(x = 3, times = args))
}
rep_it(5, times = 4)
#[1] 12 12 12 12 12
EDIT: Modified according to @Julius Vainora's suggestion
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