在 R 中扔 3 个公平的硬币 [英] Tossing 3 fair coins in R
问题描述
X = 掷三个硬币时出现正面的数量.
求 P(X=1) 和 E(X).
X = # of heads showing when three coins are tossed.
Find P(X=1), and E(X).
比如说,我想在 R 中使用 sample()
和 replicate()
函数来解决这个问题,即使有一个名为 rbinom() 的函数代码>.
Say, I want to solve this problem using sample()
, and replicate()
functions in R even though there is a function called rbinom()
.
我的尝试:
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 = ??
关于P(X),我是否在正确的轨道上?如果是,我如何找到 E(X)?
Am I on a right track regarding the P(X)? If yes, how can I find E(X)?
推荐答案
mySamples
中的结果存储每列的实验,因此您必须计算每列的 head 出现次数.概率是实验的频率/nr,而在这种情况下的平均值是频率:
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))
当你想计算一个真实的平均值时,你可以把它放到一个函数中并复制 n
次.然后平均值将成为复制的 meanOfCoinToss
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
这篇关于在 R 中扔 3 个公平的硬币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!