Here are my answers to the Week 2 Lab Activity of the couse Inferential Statistics with R presented by Coursera and conducted by Mine Çetinkaya-Rundel.
This is a R Markdown file. To a better viewing, it could be forked and knitted on RStudio to a html file or it could be viewed directly as a RPubs publication.
We will use the devtools
package to install the statsr
package associated with this course. We need to install and load this package.
install.packages("devtools")
library(devtools)
Now we can install the rest of the packages we will use during the course. Type the following commands in the Console as well:
install.packages("dplyr")
install.packages("ggplot2")
install.packages("shiny")
install_github("StatsWithR/statsr")
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(31031988)
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)
library(ggplot2)
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
samp %>%
summarise(x_bar = mean(area), s = sd(area),
med_samp = median(area),
min_samp = min(area), max_samp = max(area),
iqr_samp = IQR(area),
q1_samp = quantile(area, 0.25),
q3_samp = quantile(area, 0.75))
## # A tibble: 1 × 8
## x_bar s med_samp min_samp max_samp iqr_samp q1_samp q3_samp
## <dbl> <dbl> <dbl> <int> <int> <dbl> <dbl> <dbl>
## 1 1628.317 569.0218 1572.5 713 3500 631.75 1221.75 1853.5
ggplot(data = samp, aes(x = area)) +
geom_histogram(binwidth = 500)
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} \pm 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)))
## # A tibble: 1 × 2
## lower upper
## <dbl> <dbl>
## 1 1484.337 1772.296
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?
params$mu
## [1] 1499.69
samp %>%
summarise(lower = mean(area) - z_star_95 * (sd(area) / sqrt(n)),
upper = mean(area) + z_star_95 * (sd(area) / sqrt(n)))
## # A tibble: 1 × 2
## lower upper
## <dbl> <dbl>
## 1 1484.337 1772.296
Yes, the confidence interval captures the true average size of houses in Ames.
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)
## # A tibble: 5 × 3
## replicate lower upper
## <int> <dbl> <dbl>
## 1 1 1327.341 1677.859
## 2 2 1374.521 1617.912
## 3 3 1430.437 1700.829
## 4 4 1373.987 1693.880
## 5 5 1399.852 1654.015
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"))
ci %>%
slice(1:5)
## # A tibble: 5 × 4
## replicate lower upper capture_mu
## <int> <dbl> <dbl> <chr>
## 1 1 1327.341 1677.859 yes
## 2 2 1374.521 1617.912 yes
## 3 3 1430.437 1700.829 yes
## 4 4 1373.987 1693.880 yes
## 5 5 1399.852 1654.015 yes
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))
ci_data %>%
slice(1:10)
## ci_id ci_bounds capture_mu
## 1 1 1327.341 yes
## 2 2 1374.521 yes
## 3 3 1430.437 yes
## 4 4 1373.987 yes
## 5 5 1399.852 yes
## 6 6 1407.999 yes
## 7 7 1336.817 yes
## 8 8 1443.382 yes
## 9 9 1349.219 yes
## 10 10 1422.767 yes
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.
Grafically, we can see that 48/50 = 0.96 of the confidence intervals include the true population mean. This number is correct, since 47/50 = 0.94 and any word about half of interval is meaningless.
z_star_99 <- qnorm(0.995)
z_star_99
## [1] 2.575829
A 99% confidence level refers to the middle 99% of the distribution, and the critical value associated with this area will correspond to the 99.5th percentile.
The appropriated critical value for a 99% confidence level is 2.58.
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 95% confidence interval endpoints you had already collected. Plot all intervals and calculate the proportion of intervals that include the true population mean.
ci_99 <- 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_99 <- ci_99 %>%
mutate(capture_mu = ifelse(lower < params$mu & upper > params$mu, "yes", "no"))
ci_data_99 <- data.frame(ci_id = c(1:50, 1:50),
ci_bounds = c(ci_99$lower, ci_99$upper),
capture_mu = c(ci_99$capture_mu, ci_99$capture_mu))
ggplot(data = ci_data_99, aes(x = ci_bounds, y = ci_id,
group = ci_id, color = capture_mu)) +
geom_point(size = 2) +
geom_line() +
geom_vline(xintercept = params$mu, color = "darkgray")
Grafically, all the 50 intervals include the true population mean. That was expected since 49/50 = 0.98 and we have chosen a 99% confidence interval.
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.