4

Is there some way to access the current replication number in the replicate function so I can use it as a variable in the repeated evaluation? For example in this trivial example I'd like to use the current replication number to generate a list of variable length vectors of the current replication number. For example, x below would represent the current replicate:

replicate( 3 , rep( x , sample.int(5,1) ) )

I know this trivial example is easy to do with lapply

lapply( 1:3 , function(x) rep( x , sample.int(5,1) ) )

But can you access the replication counter in replicate?

Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • 3
    `replicate` just calls `sapply` which in turn runs `lapply`. It's a convenience function. So my guess is it's not meant for that. – Arun Apr 11 '13 at 11:03
  • 4
    ...and I think your best bet is to just `(l|s)apply` over `1:n` as you have done. I'm not sure why that would be problematic. – thelatemail Apr 11 '13 at 11:05
  • 2
    ... or just write a `for` loop. There's no time penalty and it may be easier for you to manipulate the index variable. – Carl Witthoft Apr 11 '13 at 11:31

1 Answers1

2

No, at least not in a supported, user-friendly way. As Arun put it:

> replicate
function (n, expr, simplify = "array") 
sapply(integer(n), eval.parent(substitute(function(...) expr)), 
    simplify = simplify)
...

> sapply
function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) 
{
    FUN <- match.fun(FUN)
    answer <- lapply(X = X, FUN = FUN, ...)
    ...

Now this is what sapply sees if you pass 3:

> integer(3)
[1] 0 0 0

Why don't you write your own version of replicate to use as a shortcut?

krlmlr
  • 25,056
  • 14
  • 120
  • 217