【发布时间】:2011-10-24 19:38:11
【问题描述】:
我正在编写一个蒙特卡洛模拟程序,它应该给用户相当大的灵活性。因此,我希望用户能够指定 模拟运行前随机数的具体概率分布。但是,此时用户并不知道 需要多少个随机数。
我现在的想法是从用户那里获取一个创建一个随机数的调用对象,然后在内部根据需要创建尽可能多的这些随机数。然而, 除了循环之外,我无法获得任何其他解决方案,但感觉这是因为我错过了一些东西。所以基本上,我有 两个问题:
1) 调用对象的想法是一个好的想法吗?我还在做这个项目,所以我仍然可以更改设置,但我需要一个非常直观的 为用户提供解决方案。
2) 如果这是一个好主意,是否有更优雅的方法将随机数扩展为大小为 nrMCS 的向量?
我们举个例子:
#That's 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's 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
【问题讨论】:
-
做你想做的事(虽然我认为我下面的解决方案更好)你应该使用
replicate(nrMCS,eval(rnd_call))而不是rep(...)
标签: r