使用 R 创建同时翻转 1000 次的 10 个硬币的直方图

Creating histogram for 10 coins flipped simultaneously for 1000 times using R

我是 R 的新手,刚刚从事统计 class 项目。

我必须为 10 次同时抛硬币创建直方图,共 1000 次。 这是我的代码,用于生成 1000 次翻转并根据分配计算正面数量。

# one coin toss
coin <- c('heads','tails')


tossResult = NULL
# variables to store the counts of number of heads in each toss
heads7 = 0
headsLessOrEquatTo7 = 0
headsLessThat7 = 0
heads7OrMore = 0
headsMoreThan7 = 0
heads3 = 0
heads4 = 0

for (i in 1:1000) {
    # resetting number of heads to 0 before each iteration
    numOfHeads = 0
    tossResult = sample (coin, size = 10, replace = TRUE)
    numOfHeads = sum (tossResult == 'heads')
    hist(numOfHeads)
    if (numOfHeads == 7) {
        heads7 = heads7 + 1
    } 
    if (numOfHeads <= 7) {
       headsLessOrEquatTo7 = headsLessOrEquatTo7 + 1
    } 
    if (numOfHeads < 7) {
        headsLessThat7 = headsLessThat7 + 1
    } 
    if (numOfHeads >= 7) {
        heads7OrMore = heads7OrMore + 1
    } 
    if (numOfHeads > 7) {
        headsMoreThan7 = headsMoreThan7 + 1
    }
}
print (paste0("Exactly 7 Heads:: ", heads7))
print (paste0("7 Heads or fewer:: ", headsLessOrEquatTo7))
print (paste0("Fewer than 7 Heads:: ", headsLessThat7))
print (paste0("7 Heads or more:: ", heads7OrMore))
print (paste0("More than 7 Heads:: ", headsMoreThan7))

我需要为每次迭代中的正面数量生成直方图。感谢任何帮助。

您可以创建一个函数来计算一次迭代中正面朝上的次数。

count_heads <- function() {
    tossResult = sample(c('heads','tails'), 10, replace = TRUE)
    sum(tossResult == 'heads')
}

使用replicate重复1000次并绘制直方图

hist(replicate(1000, count_heads()), xlab = "number of heads", 
      main = "Histogram of number of heads")