Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: how to use replicate() with ellipsis ...?

Tags:

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!

like image 646
Matifou Avatar asked Jan 07 '19 16:01

Matifou


1 Answers

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

like image 193
akrun Avatar answered Oct 05 '22 00:10

akrun