Create a random number vector (the size of a vector that is not known at run time)

I am programming a Monte Carlo simulation that should give the user enough flexibility. Therefore, I want the user to be able to indicate whether a specific probability distribution of random numbers is being performed before the simulation. However, at this time, the user does not know how many random numbers are needed.

Now my idea is to get a call object from a user who creates ONE random number, and then create as many of these random numbers as possible within themselves. However, apart from the cycle, I can’t get any other solution for work, but I feel that something is missing because of me. So basically, I have two questions:

1) Is the call object idea good? I am still working on a project, so I can still change the setting, but I need a very intuitive solution for the user.

2) If this is a good idea, is there a more elegant way to extend a random number to a vector of size nrMCS?

Here is an example:

#That what I would get from the user with my current set-up:
rnd_call <- call("rnorm", 1, mean=0.1, sd=0.01)
#To create nrMCS random numbers, that my best shot so far:
nrMCS <- 100
rnd_vec <- as.numeric(nrMCS)
for (i in 1:nrMCS){rnd_vec[i] <- eval(rnd_call)}
rnd_vec
[1] 0.09695170 0.11752132 0.11548925 0.11205948 0.10657986 0.12017120 0.09518435
...
#Question: Is there are more elegant way?
#I tried the following, but it fails for certain reasons
rep(eval(rnd_call), nrMCS) #DOES NOT WORK: Repeats ONE random number
[1] 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 
...
eval(rep(rnd_call, nrMCS)) #DOES NOT WORK
Error in rnorm(1, mean = 0.1, sd = 0.01, rnorm, 1, mean = 0.1, sd = 0.01,  : 
formal argument "mean" matched by multiple actual arguments
+5
source share
1 answer

I think a more idiomatic way to do this is to take a function r*and a list of arguments. Whenever you can avoid the call evalyou need. Something like that:

rnd_fun <- rnorm
rnd_args <- list(mean=0.1,sd=0.01)
nrMCS <- 100
rnd_vec <- do.call(rnd_fun,c(list(n=nrMCS),rnd_args))

(this relies on the convention in R that the first argument of a function r*(random deviation generator) is always n, the number of deviations required ...)

, rnd_fun n=nrMCS , nrMCS times...

library(rbenchmark)
nrMCS <- 10000
benchmark(single_call=do.call(rnd_fun,c(list(n=nrMCS),rnd_args)),
           mult_call=replicate(nrMCS,do.call(rnd_fun,c(list(n=1),rnd_args))))
         test replications elapsed relative user.self sys.self 
2   mult_call          100  11.135 91.27049    11.084    0.004 
1 single_call          100   0.122  1.00000     0.080    0.036
+5

All Articles