Advertisement
runnig

Sample vs Population mean

Feb 6th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.18 KB | None | 0 0
  1. TrueMean = 170
  2. TrueSD = 10
  3. PopulationSize <- 1000000
  4. Population <- rnorm(PopulationSize, mean=TrueMean, sd=TrueSD)
  5.  
  6. # SamplePercent <- 0.01
  7. # SampleSize <- PopulationSize * SamplePercent / 100.0
  8. SampleSize <- 100
  9. MySample <- sample(Population, size=SampleSize)
  10. SampleMean <- mean(MySample)
  11. SampleSD <- sd(MySample)
  12.  
  13.  
  14. hist(MySample, breaks=10, prob=TRUE, col="#DDDDDD", ylim=c(0,0.06)) #, xlab="Sample", col="grey")
  15. lines(density(Population), col="blue", lwd=1)
  16.  
  17. SDBounds <- c(SampleMean - SampleSD, SampleMean + SampleSD)
  18. vlines <- c(TrueMean, SampleMean, SDBounds)
  19. style <- c("dashed", "dotted", "solid", "solid")
  20. legend_text <- c("TrueMean", "SampleMean", "SampleMean-SD", "SampleMean+SD")
  21. my_colors = c("red", "blue", "pink")
  22. my_colors[4] = my_colors[3]
  23.  
  24. for(i in 1:length(vlines)){
  25.   abline(v=vlines[i], col=my_colors[i], lty=style[i], lwd=2)  
  26. }
  27. legend(x="topleft", legend=legend_text, col=my_colors, lty=c(1,1))
  28.  
  29. SampleMeanError <- TrueMean - SampleMean
  30.  
  31. printf <- function(...) invisible(print(sprintf(...)))
  32. printf("Population %d, Sample size %.2f%%, Estimation error: %4.4f%%",
  33.        PopulationSize, SampleSize/PopulationSize * 100, 100.0 * SampleMeanError/TrueMean)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement