1

I want to use the dots arguments (...) in an expression in replicate. I noticed that they do not have an effect doing it this way:

foo <- function(k=1, n=10, ...) 
{
  replicate(k, rnorm(n, ...))
}

foo(2, mean=100)  

Results do not have a mean of 100.

           [,1]       [,2]
[1,]  0.2859647 -0.1046510
[2,] -0.7867414  0.5347617

Using a wrapper, however, will work.

foo2 <- function(k=1, n=10, ...) 
{
  f <- function() rnorm(n, ...)
  replicate(k, f())
}

foo2(2, mean=100)  

Now, the results do have a mean of 100.

         [,1]     [,2]
[1,] 100.9644 100.6287
[2,] 100.0804 101.0218

What exactly are the mechanics going on here during the evaluation of the expr argument in replicate. Can anyone give an explanation of the behaviour?

Mark Heckmann
  • 10,943
  • 4
  • 56
  • 88

1 Answers1

1

This behavior is documented:

If expr is a function call, be aware of assumptions about where it is evaluated, and in particular what ... might refer to. You can pass additional named arguments to a function call as additional named arguments to replicate: see ‘Examples’.

And in the "Examples" section:

## use of replicate() with parameters:
foo <- function(x = 1, y = 2) c(x, y)
# does not work: bar <- function(n, ...) replicate(n, foo(...))
bar <- function(n, x) replicate(n, foo(x = x))
bar(5, x = 3)
tchakravarty
  • 10,736
  • 12
  • 72
  • 116