Tossing 3 fair coins in R

半城伤御伤魂 提交于 2019-12-11 15:37:25

问题


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)?


回答1:


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



来源:https://stackoverflow.com/questions/55054431/tossing-3-fair-coins-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!