Guest User

Untitled

a guest
Apr 12th, 2019
127
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ### Methods ###
  2. flip <- function(p){
  3. sample(0:1, 1, prob = c(1 - p, p))
  4. }
  5.  
  6. flip_n <- function(prob, n){
  7. res= NULL
  8. for(i in 1:n){
  9. res = rbind(res, flip(prob))
  10. }
  11. return(res)
  12. }
  13.  
  14. flip_til_sig <- function(prob, a = 0.05, n_min = 10, n_max = 100){
  15. res = NULL
  16. p = 1
  17. for(i in 1: n_min){
  18. res = rbind(res, flip(prob))
  19. }
  20. while(p > a & length(res) <= n_max){
  21. res = rbind(res, flip(prob))
  22. p = binom.test(sum(res), length(res), p = 0.5)$p.value
  23. }
  24. return(res)
  25. }
  26.  
  27. ### Simulation ###
  28. nsim = 1e3
  29. res1 = replicate(nsim, flip_n(prob = 0.5, n = 100), simplify = F)
  30. res2 = replicate(nsim, flip_til_sig (prob = 0.5, a = 0.05, n_min = 10, n_max = 100), simplify = F)
  31.  
  32. par(mfrow = c(2, 1))
  33. hist(sapply(res1, mean), breaks = 20, col = "Grey", xlab = "% Success", main = "Collect N datapoints")
  34. hist(sapply(res2, mean), breaks = 20, col = "Grey", xlab = "% Success", main = "Collect until stopping rule")
RAW Paste Data