Advertisement
Guest User

Untitled

a guest
Mar 14th, 2018
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. # Simulate study of treatment vs control w/ half male subjects
  2. sim = function(n, show_dat = FALSE, show_fit = FALSE){
  3. a = rnorm(n, 0.0, 1)
  4. b1 = rnorm(n/2, 0.5, 1)
  5. b2 = rnorm(n/2, 1.5, 1)
  6.  
  7. dat = data.frame(Group = c(rep("C", n), rep("T", n)),
  8. Sex = rep(c(rep("M", n/2), rep("F", n/2)), 2),
  9. Val = c(a, b1, b2))
  10.  
  11. fit = lm(Val ~ Group*Sex, dat)
  12. pvals = summary(fit)$coefficients[, 4]
  13.  
  14. if(show_dat) print(dat)
  15. if(show_fit) print(summary(fit))
  16. return(pvals)
  17. }
  18.  
  19. # Analytical power calculation by effect and sample size
  20. exactPwr = function(nvals, delta){
  21. sapply(nvals, function(n)
  22. power.t.test(n = n, delta = delta, sd = 1, sig.level = .05, strict = T)$power)
  23. }
  24.  
  25.  
  26. # Run Simulation
  27. nvals = seq(4, 100, by = 2)
  28. res = sapply(nvals, function(n) rowMeans(replicate(1e4, sim(n)) < 0.05))
  29.  
  30. # Get Sample size nearest to 80% power
  31. n80 = nvals[which.min(abs(res["GroupT",] - 0.8))]
  32.  
  33.  
  34. # Simulation Results
  35. plot(nvals, res[1, ], type = "n", ylim = range(res), xlab = "n", ylab = "% Sig", panel.first = grid())
  36. for(i in 1:nrow(res)){
  37. lines(nvals, res[i,], col = rainbow(4)[i], lwd = 3)
  38. }
  39.  
  40. # Add analytical results
  41. lines(nvals, exactPwr(nvals, 1), lwd = 2, lty = 2)
  42. lines(nvals, exactPwr(nvals, .5), lwd = 2, lty = 2)
  43.  
  44. abline(h = 0.8, v = n80, lty = 2)
  45. legend("right", c(rownames(res), "Analytic Match"),
  46. col = c(rainbow(4), "Black"), lwd = 3, lty = c(rep(1, 4), 2), bty = "n")
  47.  
  48.  
  49. res[, nvals == n80]
  50. exactPwr(nvals, .5)[nvals == n80]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement