# How do I select the expected population using runif() and rbern()

## I am a newbie in R programming: I am using the below R code using runif() and rbern() to follow the generative recipe from the diagram below that will generate 4000 draws (i.e. realizations) of the "C" random variable representing the processing time of an individual car. Of the 4,000 draws you have generated, **what percentage of the draws have a car processing time GREATER than 6 minutes? I am testing just using 4 draws and I am able to select a single value of C which is the maximum of the 4 draws. I am not sure how I can calculate the percentage =1/4 =0.25 in the below output . Can someone please suggest?  "Result=5.25363306910731"  "Result=5.26856829319149" "Result=6.4678559161257"  "Result=5.27019506809302"

Code:

library("tidyverse")
set.seed(222)
for (i in 1:4) {
rainTime = runif(n=4, min=1, max = 2)
Wash = runif(n=4, min=2, max=3)
A=Wash
preWash = runif(n=4, min=1, max=2)
B=preWash
rainFlag = rbern(4, 0.5)
x = rainFlag*rainTime
C=A+B+x
result =max(C)
outputMessage = paste0("Result=", result)
print(outputMessage)
}

Nevermind: I got the answer and hope that it helps someone

``````library("tidyverse")
> set.seed(111)
> rainTime = runif(n=4000, min=1, max = 2)
> Wash = runif(n=4000, min=2, max=3)
> A=Wash
> preWash = runif(n=4000, min=1, max=2)
> B=preWash
> rainFlag = rbern(n=4000, prob=0.5)
> x = rainFlag*rainTime
> C=A+B+x
> result =ifelse(C >6, 1,0)
> count1 = sum(result==1)
> length(result)
> proportion6 =  round(sum(result==1)/length(result),3)
> proportion6
``````

Hi mate. Great that you figure it out.

However, if you are doing a lot of simulations, there is a short and easier way to do the proportion (and to me, more easier to re-read and elegant):

This chunk of code:

``````result =ifelse(C >6, 1,0)
count1 = sum(result==1)
length(result)
proportion6 =  round(sum(result==1)/length(result),3)
proportion6
``````

is equivalent to:

``````mean(C > 6)
``````

function `mean` also estimates probabilities, not just calculates mean. If you want to know other probabilities, just use Boolean style, like if you want to know the % of values equal to 4.37, it should be `mean(C == 4.37)`

Cheers
Fer

1 Like

That's cool, thank you very much!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.