Question

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?

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top