Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. # Calculate confidence interval for given estimate and size using plug in method
  2. calc_ci = function (phat, n, level = .95) {
  3. z = qnorm((1-level)/2, lower.tail = FALSE)
  4. lower = phat - z * sqrt(phat * (1-phat) / n)
  5. upper = phat + z * sqrt(phat * (1-phat) / n)
  6. c(lower, upper)
  7. }
  8.  
  9. # Determine if true value p given falls in CI
  10. in_ci = function(ci, p) {
  11. ci[1] <= p && p <= ci[2]
  12. }
  13.  
  14. # Collects data for given m, p and the coverage of the samples
  15. stats <- data.frame(matrix(ncol = 3, nrow = 0))
  16. cnames <- c("m", "p", "coverage")
  17. colnames(stats) <- cnames
  18.  
  19. # Iterate over the target p and m values
  20. for (p in c(.5, .75, .9)) {
  21. for (m in c(10, 20, 50, 100, 250, 500)) {
  22. # Track the number of times p fals in the CI
  23. num.captured = 0
  24. iterations = 1000
  25. for (i in 1:iterations) {
  26. data.sample = rbinom(m, 1, p)
  27. phat = mean(data.sample)
  28. if (in_ci(calc_ci(phat, m), p)) {
  29. num.captured = num.captured + 1
  30. }
  31. }
  32. stats[nrow(stats) + 1,] = list(m, p, num.captured/iterations)
  33. }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement