Setting the seed

Before we do anything else, let’s set the seed so our samples will be reproducible.

set.seed(1392)

Sampling from Ames, Iowa

If you have access to data on an entire population, say the size of every house in Ames, Iowa, it’s straight forward to answer questions like, “How big is the typical house in Ames?” and “How much variation is there in sizes of houses?”. If you have access to only a sample of the population, as is often the case, the task becomes more complicated. What is your best guess for the typical size if you only know the sizes of several dozen houses? This sort of situation requires that you use your sample to make inference on what your population looks like.

The data

In the previous lab, ``Sampling Distributions’’, we looked at the population data of houses from Ames, Iowa. Let’s start by loading that data set.

load("more/ames.RData")

In this lab we’ll start with a simple random sample of size 60 from the population. Specifically, this is a simple random sample of size 60. Note that the data set has information on many housing variables, but for the first portion of the lab we’ll focus on the size of the house, represented by the variable Gr.Liv.Area.

population <- ames$Gr.Liv.Area
samp <- sample(population, 60)
  1. Describe the distribution of your sample. What would you say is the “typical” size within your sample? Also state precisely what you interpreted “typical” to mean.
hist(samp)

summary(samp)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     864    1254    1388    1478    1698    2978
mean(samp)
## [1] 1478.367

As this sample (just like the data) is somewhat right-skewed, it would be better to determine what a “typical” size within the sample is using the median instead of the mean. If we do this, the typical home size within our sample is a bit under 1400 square feet.

If we use the mean instead, the typical home size within our sample would instead be a bit under 1500 square feet.

  1. Would you expect another student’s distribution to be identical to yours? Would you expect it to be similar? Why or why not?

I would expect another student’s distribution to be similar but not identical to mine, as by chance they are going to be sampling different values. For example, they could by chance pick up an outlier value (like area < 500 square feet or >3000 square feet), which I did not find in my sample.

Confidence intervals

One of the most common ways to describe the typical or central value of a distribution is to use the mean. In this case we can calculate the mean of the sample using,

sample_mean <- mean(samp)

Return for a moment to the question that first motivated this lab: based on this sample, what can we infer about the population? Based only on this single sample, the best estimate of the average living area of houses sold in Ames would be the sample mean, usually denoted as \(\bar{x}\) (here we’re calling it sample_mean). That serves as a good point estimate but it would be useful to also communicate how uncertain we are of that estimate. This can be captured by using a confidence interval.

We can calculate a 95% confidence interval for a sample mean by adding and subtracting 1.96 standard errors to the point estimate (See Section 4.2.3 if you are unfamiliar with this formula).

se <- sd(samp) / sqrt(60)
lower <- sample_mean - 1.96 * se
upper <- sample_mean + 1.96 * se
c(lower, upper)
## [1] 1375.058 1581.676

This is an important inference that we’ve just made: even though we don’t know what the full population looks like, we’re 95% confident that the true average size of houses in Ames lies between the values lower and upper. There are a few conditions that must be met for this interval to be valid.

  1. For the confidence interval to be valid, the sample mean must be normally distributed and have standard error \(s / \sqrt{n}\). What conditions must be met for this to be true?

The typical assumptions here are that the observations are independent, and that n is >= 30. Additionally if the population distribution is not roughly normally distributed, you may need n substantially larger than 30 to get a roughly normal sampling distribution. The greater the skew, the larger the n required to get a roughly normal sampling distribution.

Confidence levels

  1. What does “95% confidence” mean? If you’re not sure, see Section 4.2.2.

95% confidence level means that if we assume that the sampling distribution of the mean is normal, the 95% confidence interval gives the interval in which the probability that the population mean is within it is 95%.

Another way to say this is that if you took a bunch of samples and their 95% confidence intervals, we would expect the population mean to be within the interval in around 95% of these samples.

In this case we have the luxury of knowing the true population mean since we have data on the entire population. This value can be calculated using the following command:

mean(population)
## [1] 1499.69
  1. Does your confidence interval capture the true average size of houses in Ames? If you are working on this lab in a classroom, does your neighbor’s interval capture this value?

Yes, the population mean of 1500 is within the 95% confidence interval of 1375-1582.

Most likely, my neighbor’s interval also captures this value. However, the whole idea of it being a 95% confidence interval is that by chance, sometimes someone will get a sample mean that is very far off from the population mean compared to other samples. So, there is some chance that my neighbor’s interval does not include the population mean.

  1. Each student in your class should have gotten a slightly different confidence interval. What proportion of those intervals would you expect to capture the true population mean? Why? If you are working in this lab in a classroom, collect data on the intervals created by other students in the class and calculate the proportion of intervals that capture the true population mean.
true_population_mean <- mean(population)

confidence_interval_includes_population_mean <- rep(NA,times=1000)

for(i in 1:1000)
{
mysample <- sample(population,60)
sample_mean <- mean(mysample)
sample_sd <- sd(mysample)
lower <- sample_mean - 1.96 * (sample_sd/sqrt(60))
upper <- sample_mean + 1.96 * (sample_sd/sqrt(60))
confidence_interval_includes_population_mean[i] <- lower <= true_population_mean & upper >= true_population_mean
}

table(confidence_interval_includes_population_mean)
## confidence_interval_includes_population_mean
## FALSE  TRUE 
##    52   948

We would expect that around 95% of those intervals would capture the true population mean.

I ran a simulation of taking 1,000 samples and confidence intervals and found that as expected, the confidence interval captured the true population mean very close to 95% of the time. Thus we confirmed our expectation.

Using R, we’re going to recreate many samples to learn more about how sample means and confidence intervals vary from one sample to another. Loops come in handy here (If you are unfamiliar with loops, review the Sampling Distribution Lab).

Here is the rough outline:

But before we do all of this, we need to first create empty vectors where we can save the means and standard deviations that will be calculated from each sample. And while we’re at it, let’s also store the desired sample size as n.

samp_mean <- rep(NA, 50)
samp_sd <- rep(NA, 50)
n <- 60

Now we’re ready for the loop where we calculate the means and standard deviations of 50 random samples.

for(i in 1:50){
  samp <- sample(population, n) # obtain a sample of size n = 60 from the population
  samp_mean[i] <- mean(samp)    # save sample mean in ith element of samp_mean
  samp_sd[i] <- sd(samp)        # save sample sd in ith element of samp_sd
}

Lastly, we construct the confidence intervals.

lower_vector <- samp_mean - 1.96 * samp_sd / sqrt(n) 
upper_vector <- samp_mean + 1.96 * samp_sd / sqrt(n)

Lower bounds of these 50 confidence intervals are stored in lower_vector, and the upper bounds are in upper_vector. Let’s view the first interval.

c(lower_vector[1], upper_vector[1])
## [1] 1322.933 1520.167

On your own

  1. Using the following function (which was downloaded with the data set), plot all intervals. What proportion of your confidence intervals include the true population mean? Is this proportion exactly equal to the confidence level? If not, explain why.

I actually was not able to download the function to plot confidence intervals with the data set, so I wrote my own code to do so.

i=1

plot(c(i,i),
c(lower_vector[i],upper_vector[i]),
type="l",
xlim=c(1,50),
ylim=range(c(lower_vector,upper_vector)),
main="Confidence intervals (50 samples)",
xlab="i",
ylab="Confidence interval range")

for(i in 2:50)
{
if(lower_vector[i] <= mean(population) & upper_vector[i] >= mean(population)){
    lines(c(i,i),
    c(lower_vector[i],upper_vector[i]),
    type="l")
    }
if(lower_vector[i] > mean(population) | upper_vector[i] < mean(population)){
    lines(c(i,i),
    c(lower_vector[i],upper_vector[i]),
    type="l",
    lwd=2,col="red")
    }   
}

abline(h=mean(population),lty=2)

Looks like 47/50, or 94% of confidence intervals include the true population mean. This proportion is very close but not exactly equal to the confidence level. One reason is that the percent of 50 confidence intervals we can get cannot be exactly 95%, as 95% of 50 is a non-integer value. So, the closest we could get would be either 94% or 96%. Also even without this, we might by chance happen to get more samples than expected with unusual values sometimes, which would make there be more than 5% of samples with confidence intervals where the population mean is outside of it.

  1. Pick a confidence level of your choosing, provided it is not 95%. What is the appropriate critical value?
-1*qnorm(.005)
## [1] 2.575829

For a confidence level of 99%, the appropriate critical value is 2.576.

  1. Calculate 50 confidence intervals at the confidence level you chose in the previous question. You do not need to obtain new samples, simply calculate new intervals based on the sample means and standard deviations you have already collected. Using the plot_ci function, plot all intervals and calculate the proportion of intervals that include the true population mean. How does this percentage compare to the confidence level selected for the intervals?
critical_value <- -1*qnorm(.005)
n=60
lower_vector <- samp_mean - critical_value * samp_sd / sqrt(n)
upper_vector <- samp_mean + critical_value * samp_sd / sqrt(n)

i=1

plot(c(i,i),
c(lower_vector[i],upper_vector[i]),
type="l",
xlim=c(1,50),
ylim=range(c(lower_vector,upper_vector)),
main="Confidence intervals (50 samples)",
xlab="i",
ylab="Confidence interval range")

for(i in 2:50)
{
if(lower_vector[i] <= mean(population) & upper_vector[i] >= mean(population)){
        lines(c(i,i),
        c(lower_vector[i],upper_vector[i]),
        type="l")
        }
if(lower_vector[i] > mean(population) | upper_vector[i] < mean(population)){
        lines(c(i,i),
        c(lower_vector[i],upper_vector[i]),
        type="l",
        lwd=2,col="red")
        }
}

abline(h=mean(population),lty=2)

Based on the confidence interval, we would expect 99% of intervals to include the true population mean. For 50 samples, this would mean we would expect all samples, or at the very least 49/50, to include the true population mean in their confidence interval (since 99% of 50 is 49.5).

Thus seeing 2/50 intervals with population mean not in the confidence intervals is a bit unusual here. The whole idea of sampling is that sometimes by chance, you can sample more of the outlier values more frequently than typical, so that’s likely what happened here.

Let’s try taking 1,000 samples and see what happens this time.

samp_mean <- rep(NA, 1000)
samp_sd <- rep(NA, 1000)
n <- 60

for(i in 1:1000){
samp <- sample(population, n) # obtain a sample of size n = 60 from the population
  samp_mean[i] <- mean(samp)    # save sample mean in ith element of samp_mean
  samp_sd[i] <- sd(samp)        # save sample sd in ith element of samp_sd
}

lower_vector <- samp_mean - critical_value * samp_sd / sqrt(n)
upper_vector <- samp_mean + critical_value * samp_sd / sqrt(n)

i=1

plot(c(i,i),
c(lower_vector[i],upper_vector[i]),
type="l",
xlim=c(1,1000),
ylim=range(c(lower_vector,upper_vector)),
main="Confidence intervals (1000 samples)\nOnly plotted for every 10th interval + intervals excl. population mean",
xlab="i",
ylab="Confidence interval range")

for(i in 2:1000)
{
if(lower_vector[i] <= mean(population) & upper_vector[i] >= mean(population) & i %% 10 == 0){
        lines(c(i,i),
        c(lower_vector[i],upper_vector[i]),
        type="l")
        }
if(lower_vector[i] > mean(population) | upper_vector[i] < mean(population)){
        lines(c(i,i),
        c(lower_vector[i],upper_vector[i]),
        type="l",
        lwd=2,col="red")
    print(paste0("Sample ",i," of 1,000 has population mean outside of confidence interval"))
        }
}
## [1] "Sample 34 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 237 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 253 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 257 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 400 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 427 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 462 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 558 of 1,000 has population mean outside of confidence interval"
## [1] "Sample 944 of 1,000 has population mean outside of confidence interval"
abline(h=mean(population),lty=2)

Taking more samples, we are less affected by getting one outlier sample. We find that the percentage of intervals that exclude the population mean is now very close to 1%.

This is a product of OpenIntro that is released under a Creative Commons Attribution-ShareAlike 3.0 Unported. This lab was written for OpenIntro by Andrew Bray and Mine Çetinkaya-Rundel.