library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.1.7 ✔ dplyr 1.0.9
## ✔ tidyr 1.2.0 ✔ stringr 1.4.0
## ✔ readr 2.1.2 ✔ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
itemSim <- setRefClass(
"itemSim",
fields = list(
s1Time = "numeric",
s2Time = "numeric",
reTime = "numeric",
tTime = "numeric"
),
methods = list(
initialize = function(reproProb){
stopifnot(is.numeric(reproProb))
s1Time <<- runif(1, 50, 100)
s2Time <<- rnorm(1, 50, 5)
reTime <<- 0
if(runif(1,0,1)<=reproProb){
reTime <<- runif(1, 20, 40)
}
tTime <<- s1Time+s2Time+reTime
}
)
)
setMethod("show",
"itemSim",
function(object){
cat("Total Time to produce this item is",object$tTime, "\n")
})
runSimulation <- function(numTrials, reproProb, timeLimit){
totalTime = list()
counter = 0
for(i in 1:numTrials){
trial = itemSim(reproProb)
totalTime <- append(totalTime, trial$tTime)
if(trial$tTime >= timeLimit){
counter = counter+1
}
}
writeLines(strwrap(paste("Total time Expected Value is", signif(mean(as.numeric(totalTime)),5))))
writeLines(strwrap(paste("Total Time STD is", signif(sd(as.numeric(totalTime)),4))))
writeLines(strwrap(paste("Probability that total time is more than", timeLimit, "is", (counter/numTrials), collapse = " ")))
return(totalTime)
}
results <- as.data.frame(as.numeric(runSimulation(10000, .05, 150))) %>%
rename(results = `as.numeric(runSimulation(10000, 0.05, 150))`)
## Total time Expected Value is 126.33
## Total Time STD is 16.46
## Probability that total time is more than 150 is 0.0633
bw <- 2*IQR(results$results)/length(results$results)^(1/3)
ggplot(results,
aes(x = results))+
geom_histogram(binwidth = bw,
fill = 'green',
color = 'black',
alpha = .5)+
labs(title = "Distribution of item Simulation",
x = "Time (Minutes)",
y = "Amount of Items")+
hrbrthemes::theme_ft_rc()
