# Fraley, Oct 2003

# Exercise for R/S+ on confidence intervals around means

# www.uic.edu/~fraley/classes/

 

# Initialize some variables. These can be changed.

 

n.studies<-20    # Number of samples to draw from population

n<-10            # Number of people in each sample

pop.mean<-10    # Average score in the population (mu)

pop.sd<-3        # Standard deviation in population (sigma)

z.crit<-1.96    # Critical value for 95% of normal distribution

 

 

# Set up some vectors for saving information

 

x.mean<-1:n.studies

ci.vec<-1:n.studies

 

# Begin loop

# In this loop, a number of samples of size n will

# be drawn from the same population. The program

# will calculate the sample mean (and save it as the ith element

# of x.mean) and half the width of the confidence interval

 

for(i in 1:n.studies){

   x<-rnorm(n,mean=pop.mean,sd=pop.sd)

   x.mean[i]<-mean(x)

   x.sd<-sqrt(var(x))

   se<-x.sd/sqrt(n)

   ci.vec[i]<-se*z.crit

}

 

# Plot results

# Plots the 95% CI for each study. A solid line

# demarcates the true parameter

 

plot(1:n.studies,x.mean,ylim=c(pop.mean-se*5,pop.mean+se*5))

abline(h=pop.mean,col=6)

 

for(i in 1:n.studies){

   lines(c(i,i),c((x.mean[i]-ci.vec[i]),(x.mean[i]+ci.vec[i])) )

}