I'm trying to generate several series of random numbers, each series with a different set of parameters. Then I want to replicate all of that. I want to have a function to do this, and it seems like it should be a 1-liner with something like rnorm()
to generate the numbers, mapply()
to generate those numbers for several parameter sets, and replicate()
to repeat the whole process.
To achieve that, I wrote a function whose ...
arguments I want to correspond to the ...
in mapply
, but it appears that ...
is being ignored by mapply
. I have some examples that should clarify my desired output, as well as the problem:
# Some values to be passed to the ... of mapply
mus <- c(-30, 0, 30)
sds <- c(0.1, 1, 10)
# =================================
# = What I want, if it would work =
# =================================
f <- function(n=3, ...){
replicate(2, mapply(rnorm, MoreArgs=list(n=n), ...))
}
f(mean=mus, sd=sds) # Doesn't work :(
>, , 1
>
> [,1]
>[1,] -0.4901243
>[2,] 0.8268027
>[3,] -0.4829781
>
>, , 2
>
> [,1]
>[1,] -0.02025903
>[2,] -1.57011537
>[3,] 0.49234503
# ==========================================================
# = What I can currently get to work, but not style I want =
# ==========================================================
# I can't understand why f.inside is needed!
f2 <- function(n=3, ...){
f.inside <- function() mapply(rand.gen, MoreArgs=list(n=n), ...)
replicate(2, f.inside())
}
f2(mean=mus, sd=sds) # Desired output
>, , 1
>
> [,1] [,2] [,3]
>[1,] -29.83762 -0.06138165 9.956601
>[2,] -30.04880 1.39123405 33.036675
>[3,] -29.94070 -1.15741513 19.337497
>[4,] -29.92360 0.74300731 38.741367
>[5,] -29.81723 0.84565813 22.261605
>
>, , 2
>
> [,1] [,2] [,3]
>[1,] -30.01407 -0.5198845 20.85942
>[2,] -29.77586 -0.1705062 22.06274
>[3,] -29.96901 -0.4412471 21.42849
>[4,] -30.04079 0.4230790 28.35480
>[5,] -30.04794 0.3000821 50.09012
I'm guessing I need to wrap the ...
in something; I've haphazardly tried things like alist()
, list()
, bquote()
, expression()
, as.call()
and several other failed approaches.
1) Why does
EDIT: This was an ancillary question, to which the answer is "dots don't work with replicate". OK, on to the core question...mapply
in f()
appear to completely ignore the ...
?
# =====================================
# = OK, Function for Refined Question =
# =====================================
f.edit <- function(n=3, ...){
l <- list(...)
replicate(2,mapply(rnorm, MoreArgs=list(n=n), l))
}
f.edit(mean=mus, sd=sds) # Doesn't work :(
2) How do I split the elements of an object into length(object) elements, and pass those as separate items to mapply
's ...
?
I need to get better at my ellipses. I'm really stumped on this one.