Complete all Exercises, and submit answers to Questions on the Coursera platform.
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.
Setting a seed: We will take some random samples and calculate confidence based on these samples in this lab, which means you should set a seed on top of your lab. If this concept is new to you, review the previous lab and ask your TA.
Setting a seed will cause R to sample the same sample each time you knit your document. This will make sure your results don’t change each time you knit, and it will also ensure reproducibility of your work (by setting the same seed it will be possible to reproduce your results). You can set a seed like this:
set.seed(23549387) # make sure to change the seed
The number above is completely arbitraty. If you need inspiration, you can use your ID, birthday, or just a random string of numbers. The important thing is that you use each seed only once. You only need to do this once in your R Markdown document, but make sure it comes before sampling.
In this lab we will explore the data using the dplyr
package and visualize it using the ggplot2
package for data visualization. The data can be found in the companion package for this course, statsr
.
Let’s load the packages.
library(statsr)
library(dplyr)
## Warning: package 'dplyr' was built under R version 3.2.5
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.2.5
We consider real estate data from the city of Ames, Iowa. This is the same dataset used in the previous lab. The details of every real estate transaction in Ames is recorded by the City Assessor’s office. Our particular focus for this lab will be all residential home sales in Ames between 2006 and 2010. This collection represents our population of interest. In this lab we would like to learn about these home sales by taking smaller samples from the full population. Let’s load the data.
data(ames)
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 area
.
n <- 60
samp <- sample_n(ames, n)
Exercise: Describe the distribution of homes in your sample. What would you say is the “typical” size within your sample? Also state precisely what you interpreted “typical” to mean.
# type your code for the Exercise here, and Knit
hist(samp$area)
my_xbar <- mean(samp$area)
cat(sprintf('sample average: %6.3f',my_xbar))
## sample average: 1515.917
se <- sd(samp$area)/sqrt(n)
cat(sprintf('Standard Error of the mean: %6.3f',se))
## Standard Error of the mean: 55.579
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 x_bar
). That serves as a good point estimate but it would be useful to also communicate how uncertain we are of that estimate. This uncertainty can be quantified using a confidence interval.
A confidence interval for a population mean is of the following form \[ \bar{x} + z^\star \frac{s}{\sqrt{n}} \]
You should by now be comfortable with calculating the mean and standard deviation of a sample in R. And we know that the sample size is 60. So the only remaining building block is finding the appropriate critical value for a given confidence level. We can use the qnorm
function for this task, which will give the critical value associated with a given percentile under the normal distribution. Remember that confidence levels and percentiles are not equivalent. For example, a 95% confidence level refers to the middle 95% of the distribution, and the critical value associated with this area will correspond to the 97.5th percentile.
We can find the critical value for a 95% confidence interal using
z_star_95 <- qnorm(0.975)
z_star_95
## [1] 1.959964
which is roughly equal to the value critical value 1.96 that you’re likely familiar with by now.
Let’s finally calculate the confidence interval:
samp %>%
summarise(lower = mean(area) - z_star_95 * (sd(area) / sqrt(n)),
upper = mean(area) + z_star_95 * (sd(area) / sqrt(n)))
## Source: local data frame [1 x 2]
##
## lower upper
## <dbl> <dbl>
## 1 1406.985 1624.849
To recap: 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.
In this case we have the rare luxury of knowing the true population mean since we have data on the entire population. Let’s calculate this value so that we can determine if our confidence intervals actually capture it. We’ll store it in a data frame called params
(short for population parameters), and name it mu
.
params <- ames %>%
summarise(mu = mean(area))
Exercise: Does your confidence interval capture the true average size of houses in Ames?
# type your code for the Exercise here, and Knit
my_ci <- c(my_xbar - z_star_95 * se,
my_xbar + z_star_95 * se)
if (params$mu <= my_ci[2] & params$mu >= my_ci[1]){print('Yes')
} else {print('Not')}
## [1] "Yes"
Using R, we’re going to collect many samples to learn more about how sample means and confidence intervals vary from one sample to another.
Here is the rough outline:
We can accomplish this using the rep_sample_n
function. The following lines of code takes 50 random samples of size n
from population (and remember we defined \(n = 60\) earlier), and computes the upper and lower bounds of the confidence intervals based on these samples.
ci <- ames %>%
rep_sample_n(size = n, reps = 50, replace = TRUE) %>%
summarise(lower = mean(area) - z_star_95 * (sd(area) / sqrt(n)),
upper = mean(area) + z_star_95 * (sd(area) / sqrt(n)))
Let’s view the first five intervals:
ci %>%
slice(1:5)
## Source: local data frame [5 x 3]
##
## replicate lower upper
## <int> <dbl> <dbl>
## 1 1 1372.274 1625.526
## 2 2 1397.113 1660.587
## 3 3 1462.772 1732.262
## 4 4 1408.189 1648.611
## 5 5 1427.290 1652.810
Next we’ll create a plot similar to Figure 4.8 on page 175 of OpenIntro Statistics, 3rd Edition. First step will be to create a new variable in the ci
data frame that indicates whether the interval does or does not capture the true population mean. Note that capturing this value would mean the lower bound of the confidence interval is below the value and upper bound of the confidence interval is above the value. Remember that we create new variables using the mutate
function.
ci <- ci %>%
mutate(capture_mu = ifelse(lower < params$mu & upper > params$mu, "yes", "no"))
The ifelse
function is new. It takes three arguments: first is a logical statement, second is the value we want if the logical statement yields a true result, and the third is the value we want if the logical statement yields a false result.
We now have all the information we need to create the plot, but we need to re-organize our data a bit for easy plotting. Specifically, we need to organize the data in a new data frame where each row represents one bound, as opposed to one interval. So this
lower upper capture_mu
1 1350.540 1544.360 yes
2 1333.441 1584.425 yes
3 1412.133 1663.801 yes
...
should instead look like
ci_id ci_bounds capture_mu
1 1 1350.540 yes
2 2 1333.441 yes
3 3 1412.133 yes
4 1 1544.360 yes
5 2 1584.425 yes
6 3 1663.801 yes
...
We can accomplish this using the following:
ci_data <- data.frame(ci_id = c(1:50, 1:50),
ci_bounds = c(ci$lower, ci$upper),
capture_mu = c(ci$capture_mu, ci$capture_mu))
And finally we can create the plot using the following:
ggplot(data = ci_data, aes(x = ci_bounds, y = ci_id,
group = ci_id, color = capture_mu)) +
geom_point(size = 2) + # add points at the ends, size = 2
geom_line() + # connect with lines
geom_vline(xintercept = params$mu, color = "darkgray") # draw vertical line
Exercise: What proportion of your confidence intervals include the true population mean? Is this proportion exactly equal to the confidence level? If not, explain why.
# type your code for the Question 5 here, and Knit
z_star_99 <- qnorm(.99+.5*(1-.99))
cat(z_star_99)
## 2.575829
Exercise: Calculate 50 confidence intervals at the 99% confidence level. You do not need to obtain new samples, simply calculate new intervals based on the sample means and standard deviations you have already collected. Plot all intervals and calculate the proportion of intervals that include the true population mean.
# type your code for the Exercise here, and Knit
ci <- ames %>%
rep_sample_n(size = n, reps = 50, replace = TRUE) %>%
summarise(lower = mean(area) - z_star_99 * (sd(area) / sqrt(n)),
upper = mean(area) + z_star_99 * (sd(area) / sqrt(n)))
ci <- ci %>%
mutate(capture_mu = ifelse(lower < params$mu & upper > params$mu, "yes", "no"))
ci_data <- data.frame(ci_id = c(1:50, 1:50),
ci_bounds = c(ci$lower, ci$upper),
capture_mu = c(ci$capture_mu, ci$capture_mu))
ggplot(data = ci_data, aes(x = ci_bounds, y = ci_id,
group = ci_id, color = capture_mu)) +
geom_point(size = 2) + # add points at the ends, size = 2
geom_line() + # connect with lines
geom_vline(xintercept = params$mu, color = "darkgray") # draw vertical line
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.