1

I need to use replicate inside a custom function (the details are not important but it involves random number generation.

Let's say I'm using: rnorm(2)

I know I can repeat the expression 10 times using replicate(10, rnorm(2))

Now, I want to be able to use replicate inside a function since I need to post-process the output and I also want to be able to change the replicated expression, so I'm trying something like this:

fn <- function(expression) replicate(10, expression)

But when I run the function I get the exact same numbers repeated 10 times:

fn(rnorm(2))

I know that fn is getting the result of rnorm(2) and that's why it is repeating the numbers so I need to tell fn not to evaluate expression. I've been digging into this and it seems I need to use substitute inside fn but I can't make it work.

Eduardo
  • 1,383
  • 8
  • 13
  • 2
    Would you be unsatisfied with `fn1 <- function(FUN,...){ sapply(seq_len(10),FUN = FUN,...)}; fn1(rnorm,n = 2)`? – joran Sep 08 '16 at 03:48
  • I want to pass parameters to the expression but also outside it (like the number times to replicate), so I did: `myfn <- function(a, b, c) a*b*rnorm(c); fn1 <- function(times, FUN, ...){ sapply(seq_len(times), FUN=FUN, ...)}; fn1(times=10, FUN=myfn, 1, 2, 3)`; but I'm getting: `Error in FUN(X[[i]], ...) : unused argument (3)` any idea why this doesn't work? – Eduardo Sep 08 '16 at 23:55

1 Answers1

4

If you just want to pass thought the expression, you can use ... like

fn <- function(...) replicate(10, ...)

That doesn't allow you to interact with that particular parameter and it assumes that you want to pass along all parameters.

You could capture the expression and pass it along with

fn <- function(a) do.call("replicate", list(10, substitute(a)))

as well. You need to use do.call to get pass along the unevaluated expression to `replicate.

MrFlick
  • 195,160
  • 17
  • 277
  • 295