0 = Tails and 1 = Heads
library(matlib)
library(MASS)
library(dplyr)
library(ggplot2)
# Function to Randomly perform coin toss
CoinToss <- function(n=10){
e <- sample(0:1,n,rep=T)
e0 <- sum(e==0)
print("The no. of Tails :")
print(e0)
print("The probability of Tails :")
print(round(e0/n,2))
e1 <- sum(e ==1)
print("The no. of Heads :")
print(e1)
print("The probability of Heads :")
print(round(e1/n,2))
df <- data.frame(e0,e1,e)
dfnew <-df %>% rename(Tails=e0, Heads=e1, Outcome = e)
dfnew1 <- dfnew %>% mutate(Outcome = ifelse(Outcome==0,"Tails", ifelse(Outcome ==1, "Heads", NA)))
#plot histogram of OUtcomes
ggplot(data = dfnew1) +
geom_bar(mapping = aes(x = Outcome, y = ..prop.., group = 1), stat = "count") +
scale_y_continuous(labels = scales::percent_format())
}
Observations:
# Ten coin tosses
CoinToss(10)
## [1] "The no. of Tails :"
## [1] 4
## [1] "The probability of Tails :"
## [1] 0.4
## [1] "The no. of Heads :"
## [1] 6
## [1] "The probability of Heads :"
## [1] 0.6
# Fifty coin tosses
CoinToss(50)
## [1] "The no. of Tails :"
## [1] 20
## [1] "The probability of Tails :"
## [1] 0.4
## [1] "The no. of Heads :"
## [1] 30
## [1] "The probability of Heads :"
## [1] 0.6
#one hundredcoin tosses
CoinToss(100)
## [1] "The no. of Tails :"
## [1] 58
## [1] "The probability of Tails :"
## [1] 0.58
## [1] "The no. of Heads :"
## [1] 42
## [1] "The probability of Heads :"
## [1] 0.42
#1 million coin tosses
CoinToss(1000000)
## [1] "The no. of Tails :"
## [1] 499609
## [1] "The probability of Tails :"
## [1] 0.5
## [1] "The no. of Heads :"
## [1] 500391
## [1] "The probability of Heads :"
## [1] 0.5