首页 > 解决方案 > Tossing 3 fair coins in R

问题描述

X = # of heads showing when three coins are tossed.
Find P(X=1), and E(X).

Say, I want to solve this problem using sample(), and replicate() functions in R even though there is a function called rbinom().

My attempt:

noOfCoinTosses = 3;
noOfExperiments = 5;
mySamples <-replicate(noOfExperiments,
                    {mySamples <- sample(c("H", "T"), noOfCoinTosses, replace = T, prob=c(0.5, 0.5))
                    })
headCount = length(which(mySamples=="H"))
probOfCoinToss <- headCount / noOfExperiments   # 1.6
meanOfCoinToss = ??

Am I on a right track regarding the P(X)? If yes, how can I find E(X)?

标签: rprobability

解决方案


The results in mySamples stores the experiments per column, so you'll have to count the occurrence of head per column. The probability is then the frequency / nr of experiments, while the mean in this case is the frequency:

noOfCoinTosses = 3;
noOfExperiments = 5;
mySamples <-replicate(noOfExperiments,
                      {mySamples <- sample(c("H", "T"), noOfCoinTosses, replace = T, prob=c(0.5, 0.5))
                      })
headCount <- apply(mySamples,2, function(x) length(which(x=="H")))
probOfCoinToss <- length(which(headCount==1)) / noOfExperiments   # 1.6
meanOfCoinToss <- length(which(headCount==1))

When you want to calculate a real mean, you can put this into a function and replicate that n times. Then the mean will become the average of the replicated meanOfCoinToss


推荐阅读