### This is a program by Matthew Berman. ### Suppose we take a sample of size n = 31 from a Normal population with mean 2 ### and standard deviation 3, where both mu and sigma are both unknown. To calculate a 95% Confidence ### Interval for mu we use the standard t-interval formula. To show that the 95% ### confidence level is correct we simulate random samples from the population and ### compute the C.I.'s for each sample and check the coverage. We should expect to ### see 95% of the intervals cover mu. ####################################################################### # R is number of samples R <- 1000 # N is number of observations per sample N <- 31 # 31 was chosen so that the t-statistic will have 30 df mu <- 2 #arbitrary value of mu sigma <- 3 #arbitrary value of sigma count <- 0 zstar <- qnorm(0.975) #(for a 95% C.I. with normal dist.) tstar <- qt(0.975,df = 30) #(for a 95% C.I. with t dist., 30 df) for(i in 1:R){ x <- rnorm(N,mu,sigma) xbar <- mean(x) xsd <- sqrt(var(x)) UCL <- xbar + tstar * xsd / sqrt(N) LCL <- xbar - tstar * xsd / sqrt(N) if( mu > LCL && mu < UCL) count <- count + 1 ; } count #this number is near 950 count/R #this number is near 0.95