在 R 中扔 3 个公平的硬币 [英] Tossing 3 fair coins in R

查看:41
本文介绍了在 R 中扔 3 个公平的硬币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆