Search code examples
rstatisticsprobability

Creating histogram for 10 coins flipped simultaneously for 1000 times using R


I am new to R and just working on a statistics class project.

I have to create a histogram for 10 simultaneous coin flips, 1000 times. Here is my code for generating the 1000 flips and counting number of heads based on the assignment.

# one coin toss
coin <- c('heads','tails')


tossResult = NULL
# variables to store the counts of number of heads in each toss
heads7 = 0
headsLessOrEquatTo7 = 0
headsLessThat7 = 0
heads7OrMore = 0
headsMoreThan7 = 0
heads3 = 0
heads4 = 0

for (i in 1:1000) {
    # resetting number of heads to 0 before each iteration
    numOfHeads = 0
    tossResult = sample (coin, size = 10, replace = TRUE)
    numOfHeads = sum (tossResult == 'heads')
    hist(numOfHeads)
    if (numOfHeads == 7) {
        heads7 = heads7 + 1
    } 
    if (numOfHeads <= 7) {
       headsLessOrEquatTo7 = headsLessOrEquatTo7 + 1
    } 
    if (numOfHeads < 7) {
        headsLessThat7 = headsLessThat7 + 1
    } 
    if (numOfHeads >= 7) {
        heads7OrMore = heads7OrMore + 1
    } 
    if (numOfHeads > 7) {
        headsMoreThan7 = headsMoreThan7 + 1
    }
}
print (paste0("Exactly 7 Heads:: ", heads7))
print (paste0("7 Heads or fewer:: ", headsLessOrEquatTo7))
print (paste0("Fewer than 7 Heads:: ", headsLessThat7))
print (paste0("7 Heads or more:: ", heads7OrMore))
print (paste0("More than 7 Heads:: ", headsMoreThan7))

I need to produce the histogram for the number of heads in each iteration. Any help is appreciated.


Solution

  • You could create a function that counts number of heads in one iteration.

    count_heads <- function() {
        tossResult = sample(c('heads','tails'), 10, replace = TRUE)
        sum(tossResult == 'heads')
    }
    

    Use replicate to repeat it 1000 times and plot histogram

    hist(replicate(1000, count_heads()), xlab = "number of heads", 
          main = "Histogram of number of heads")
    

    enter image description here