运行 在 R 中不使用循环的模拟

Running a simulation without using looping in R

我有以下用于 Monte Carlo 模拟的代码:

function (muC1,sigmaC1,muC2,sigmaC2,Msim=10000) { 
# a grand loop simulation program for the lifetime of 
# a simple system of components. This system has 
# two branches. The first branch fails when C1 fails.   
# The second branch fails as soon as either of C2 or C3 fails.
#
# get alpha's and lambda's for Gamma lifetime RVs from the 
# mu's and sigma's.
# Note C2 has the same distribution as C3, i.e. 
# alpha3=alpha2, lambda3=lambda2
lambda1 = muC1/sigmaC1^2
alpha1 = muC1*lambda1
lambda2 = muC2/sigmaC2^2
alpha2 = muC2*lambda2
#  
# initialize simulation summary holders
count.C1fail = 0   # number of times C1 fails before branch2
system.lifetime = rep(NA,Msim)
#
# begin grand loop
for (i in 1:Msim) {
C1 = rgamma(1,alpha1,lambda1)
C2 = rgamma(1,alpha2,lambda2)
C3 = rgamma(1,alpha2,lambda2)
branch2 = min(C2,C3)
system.lifetime[i] = max(C1,branch2)
if (C1 < branch2) count.C1fail = count.C1fail+1
} # end grand loop
#
# final summary calculations and wrapup
PC1fail = count.C1fail/Msim
hist(system.lifetime,main="Simulated System Lifetimes")
meanL = mean(system.lifetime)
stddevL = sd(system.lifetime)
MOEL95pct = 1.96*stddevL/sqrt(Msim)
out = list(muC1,sigmaC1,muC2,sigmaC2,Msim,PC1fail,meanL,MOEL95pct)
names(out) = c("muC1","sigmaC1","muC2","sigmaC2","Msim","PC1fail","meanL","MOEL95pct")
out 
} 

此模拟非常适合我的需要,但对于一项作业,我需要 运行 相同的模拟(muC1 = 100、sigmaC1 = 20、muC2 = 80、sigmaC2 = 40、Msim = 10000)没有大循环。有小费吗?

您可以通过一次绘制所有随机值来消除循环。

C1 <- rgamma(Msim, alpha1, lambda1)
C2 <- rgamma(Msim, alpha2, lambda2)
C3 <- rgamma(Msim, alpha2, lambda2)
branch2 <- pmin(C2, C3)
system.lifetime <- pmax(C1, branch2)
count.C1fail <- sum(C1 < branch2)

然后因为我们想对向量而不是两个值进行操作,我们从 minmax 切换到 pminpmax(向量化版本功能)。最后,为了计算向量中的事件,我们通常只是 sum() 超过 TRUE/FALSE 值,因为 TRUE 被转换为 1 和 FALSE 0 所以我们只得到 TRUE 事件的计数。

这样做也意味着不需要提前初始化count.C1failsystem.lifetime