创建一个充当计数器但计数器未正确计数的for循环

时间:2019-01-23 20:40:55

标签: r

我有一个for循环,在4个骰子掷骰游戏中,每当它返回至少在游戏中赢得1 6的胜利时,该循环都会计数。但是,当我进行多次重复运行时,我的计数器最多只能计数到1。

sixes_rep <- function(n=4, r){
  total=0
  for (i in 1:r){
    if (any(ceiling(6*runif(n)) == 6)){
      total=total+1
       }
    } 
    # n is the number of dice
    # r is the number of replicates (capital N in the text)
    obs <-(total/r)

    theor <- (1-(5/6)^n)
    difference <- obs-theor


    cat("Theoretical prob of at least one six in", n, "dice is:", theor, "\n")
    cat("Empirical prob of at least one six after", r,"replications is:", obs, "\n")
    cat("the difference is", difference ,"\n")
    cat("trues",total)
    return(difference)
  }
}

# Sample output:
# Theoretical prob of at least one six in 4 dice is: 0.5177469 
# Empirical prob of at least one six after 10000 replications is: 0.5175 
# the difference is -0.0002469136 
# do not modify this code chunk
# a few test cases to see if your code works
set.seed(1)
sixes_rep(4, 100)
sixes_rep(4, 100)
sixes_rep(4, 1000)
sixes_rep(4, 1000)
sixes_rep(4, 1000)
sixes_rep(4, 10000)
sixes_rep(4, 10000)
sixes_rep(4, 10000)

1 个答案:

答案 0 :(得分:0)

您不需要显式的for循环,下面的代码使用replicate进行同样的操作,并且更具可读性。

sixes_rep <- function(n = 4, r){
  draws <- replicate(r, sample(6, 4, TRUE))
  total <- sum(draws == 6)
  obs <- total/r

  theor <- 1 - (5/6)^n
  difference <- obs - theor

  cat("Theoretical prob of at least one six in", n, "dice is:", theor, "\n")
  cat("Empirical prob of at least one six after", r, "replications is:", obs, "\n")
  cat("the difference is", difference ,"\n")
  cat("trues", total, "\n")
  return(difference)
}