I think it's important to first have a full-running simulation work 1 time. To do that and honor your "stop if the totalTime >= 6", you need something like a while
loop.
I suggest writing a function that does this one thing very well and returns the two variables you want (cost and total time). Once you have that, it's trivial to replicate it.
simfunc <- function(shape = 2, scale = 0.5, unitCost = 100) {
cost <- 0
totalTime <- 0
while (totalTime < 6) {
failureTime <- rgamma(1, shape = shape, scale = scale)
if (failureTime > 1) {
cost <- cost + unitCost
}
totalTime <- totalTime + failureTime
}
c(cost = cost, totalTime = totalTime)
}
set.seed(42)
simfunc()
# cost totalTime
# 200.00 6.86
simfunc()
# cost totalTime
# 400.00 6.79
simfunc()
# cost totalTime
# 300.00 6.95
From here, we can replicate it easily:
set.seed(42)
replicate(10, simfunc())
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# cost 200.00 400.00 300.00 300.00 200.00 300.00 300.00 200 400.00 300.00
# totalTime 6.86 6.79 6.95 6.62 6.34 6.81 7.14 6 6.73 6.75
(To summarize, store that in a variable and aggregate the row you need. You might find it easier to visualize if you t
ranspose it to be columnar, and perhaps convert to a data.frame
, but that's only for your aesthetic benefit, the stats will be the same regardless.)
Also, I'm inferring that you may want totalTime
, since often simulations like this not only want to know cost over the system's life-cycle, but also the mean-time between fails and some analysis of that. In this case, it appears you've already figured that out (based on your scale=
and shape=
parameters), but it can be interesting anyway.