Understanding confidence intervals through simulation

Confidence intervals for the mean in a normal population with known variance


Function to create graphs like in the shinny app

plotsimul<-function(mu,sigma,n,conf,numsim){
  a<-qnorm((100-conf)/200, mean = 0, sd = 1, lower.tail = TRUE)
  samples<-NULL; extinf<-NULL; extsup<-NULL; include<-0
  for (i in 1:numsim){
      samples[[i]]<-rnorm(n, mean = mu, sd = sigma)
      extinf[i]<-mean(samples[[i]])+a*sigma/sqrt(n); extsup[i]<-mean(samples[[i]])-a*sigma/sqrt(n)
      if ((extinf[i]<mu) & (extsup[i]>mu)) include<-include+1}
  int<-cbind(extinf,extsup)
  percent<-include*100/numsim
  muestra<-rep(NULL,1+numsim)
  plot(muestra, xlim=c(-15,15), ylim=c(-6,1+numsim), xlab='', ylab='',main='')
  for (i in 1:numsim) segments(int[i,1], i, int[i,2], i, col = "#3399CC")
  abline(v=mu, col = "#FF6600", lty=1, lwd=2)
    text(mu+1.6, -3, paste("True mean value"),col = "#FF6600")
    mtext(paste("Intervals containing the mean = ", round(percent, 2),"%"),line= 1.5,cex=1.3,col = "#3366CC")}

Influence of the confidence level

Given the variance and the sample size, a larger confidence level leads to wider intervals.

par(mfrow = c(1, 2))
plotsimul(1,3,10,90,100); mtext("variance=9, n=10, confidence level=90%")
plotsimul(1,3,10,99,100); mtext("variance=9, n=10, confidence level=99%")

plot of chunk figure1

Influence of the sample size

Given the variance and the confidence level, a larger sample size leads to narrower intervals.

par(mfrow = c(1, 2))
plotsimul(1,3,10,90,100); mtext("variance=9, n=10, confidence level=90%")
plotsimul(1,3,50,90,100); mtext("variance=9, n=50, confidence level=90%")

plot of chunk figure2

Influence of the variance

Given the sample size and the confidence level, a larger variance leads to wider intervals.

par(mfrow = c(1, 2))
plotsimul(1,3,10,90,100); mtext("variance=9, n=10, confidence level=90%")
plotsimul(1,6,10,90,100); mtext("variance=36, n=10, confidence level=90%")

plot of chunk figure3