r - 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)?
解决方案
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
推荐阅读
- android - MainActivity.java 中的 NonNull 问题
- reactjs - 带有 React 的 ASP.NET Core Identity SPA
- javascript - 将 Javascript 作为 Firebase 函数中的文本提供
- c++ - 在 Hackerearth 上出现运行时错误(SIGSEGV),无法找出代码中的问题
- r - 使重新导出的函数的 `?` 引用原始函数
- javascript - 在减少 Chrome 扩展中的全局变量使用方面需要帮助
- database - 发布项目,包括数据库,其中每次在 Visual Basic 中打开项目时都会更新数据库
- r - R如何根据大小类过滤时间序列人口统计数据库
- java - Recycle view onScrollChange listener keep triggering rappedly
- android - UnsatisfiedLinkError OkHttpClient API 19