Practical exercises with answers

Lets set the seed to keep the answers consistent as we knit the data.

set.seed(100)               

Load packages

library(statsr)
library(dplyr)
library(ggplot2)

Getting Started

The data

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
colnames(ames)
##  [1] "Order"           "PID"             "area"            "price"          
##  [5] "MS.SubClass"     "MS.Zoning"       "Lot.Frontage"    "Lot.Area"       
##  [9] "Street"          "Alley"           "Lot.Shape"       "Land.Contour"   
## [13] "Utilities"       "Lot.Config"      "Land.Slope"      "Neighborhood"   
## [17] "Condition.1"     "Condition.2"     "Bldg.Type"       "House.Style"    
## [21] "Overall.Qual"    "Overall.Cond"    "Year.Built"      "Year.Remod.Add" 
## [25] "Roof.Style"      "Roof.Matl"       "Exterior.1st"    "Exterior.2nd"   
## [29] "Mas.Vnr.Type"    "Mas.Vnr.Area"    "Exter.Qual"      "Exter.Cond"     
## [33] "Foundation"      "Bsmt.Qual"       "Bsmt.Cond"       "Bsmt.Exposure"  
## [37] "BsmtFin.Type.1"  "BsmtFin.SF.1"    "BsmtFin.Type.2"  "BsmtFin.SF.2"   
## [41] "Bsmt.Unf.SF"     "Total.Bsmt.SF"   "Heating"         "Heating.QC"     
## [45] "Central.Air"     "Electrical"      "X1st.Flr.SF"     "X2nd.Flr.SF"    
## [49] "Low.Qual.Fin.SF" "Bsmt.Full.Bath"  "Bsmt.Half.Bath"  "Full.Bath"      
## [53] "Half.Bath"       "Bedroom.AbvGr"   "Kitchen.AbvGr"   "Kitchen.Qual"   
## [57] "TotRms.AbvGrd"   "Functional"      "Fireplaces"      "Fireplace.Qu"   
## [61] "Garage.Type"     "Garage.Yr.Blt"   "Garage.Finish"   "Garage.Cars"    
## [65] "Garage.Area"     "Garage.Qual"     "Garage.Cond"     "Paved.Drive"    
## [69] "Wood.Deck.SF"    "Open.Porch.SF"   "Enclosed.Porch"  "X3Ssn.Porch"    
## [73] "Screen.Porch"    "Pool.Area"       "Pool.QC"         "Fence"          
## [77] "Misc.Feature"    "Misc.Val"        "Mo.Sold"         "Yr.Sold"        
## [81] "Sale.Type"       "Sale.Condition"
summary(samp$area)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     334    1080    1374    1447    1773    2646
## Another way to calculate this information. 
#ames %>%
#    summarise(mu = mean(area), sigma = sd(area), pop_med = median(area), 
#              pop_iqr = IQR(area), pop_q1 = quantile(area, .25), 
#              pop_q3 = quantile(area, .75), pop_min = min(area), 
#              pop_max = max(area))

##Let's take a look at the data
ggplot(samp,aes(x=area, color = "black")) +
    geom_histogram(binwidth = 200, fill = "red") +
    ggtitle("Number of House by Area")

  1. True or False: My distribution should be similar to others’ distributions who also collect random samples from this population, but it is likely not exactly the same since it’s a random sample.
    1. True.
    2. False.
    3. Answer : True

TRUE

Confidence intervals

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 interval 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 x 2
##   lower upper
##   <dbl> <dbl>
## 1 1323. 1572.

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.

  1. For the confidence interval to be valid, the sample mean must be normally distributed and have standard error \(s / \sqrt{n}\). Which of the following is not a condition needed for this to be true?
    1. The sample is random.
    2. The sample size, 60, is less than 10% of all houses.
    3. The sample distribution must be nearly normal.
    4. The answer is that the sample distribution must be normal is false because the sample size is sufficiently large(60).

Confidence levels

  1. What does “95% confidence” mean?
    1. 95% of the time the true average area of houses in Ames, Iowa, will be in this interval.
    2. 95% of random samples of size 60 will yield confidence intervals that contain the true average area of houses in Ames, Iowa.
    3. 95% of the houses in Ames have an area in this interval.
    4. 95% confident that the sample mean is in this interval.
    5. We expect that “95% of random samples of size 60 will yield confidence intervals that contain the true average area of houses in Ames, Iowa.”

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
## # A tibble: 1 x 1
##      mu
##   <dbl>
## 1 1500.
  1. What proportion of 95% confidence intervals would you expect to capture the true population mean?
    1. 1%
    2. 5%
    3. 95%
    4. 99%
    5. We expect that 95% of “95% confidence intervals” would capture the true population mean.

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)))
## `summarise()` ungrouping output (override with `.groups` argument)

Let’s view the first five intervals:

ci %>%
  slice(1:5)
## # A tibble: 5 x 3
##   replicate lower upper
##       <int> <dbl> <dbl>
## 1         1 1353. 1632.
## 2         2 1398. 1703.
## 3         3 1353. 1629.
## 4         4 1338. 1591.
## 5         5 1439. 1763.

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))

ci_data %>%
  slice(1:10)
##    ci_id ci_bounds capture_mu
## 1      1  1352.864        yes
## 2      2  1397.686        yes
## 3      3  1352.889        yes
## 4      4  1337.832        yes
## 5      5  1438.963        yes
## 6      6  1353.049        yes
## 7      7  1439.422        yes
## 8      8  1287.370         no
## 9      9  1358.157        yes
## 10    10  1284.203        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.

  1. What is the appropriate critical value for a 99% confidence level?
    1. 0.01
    2. 0.99
    3. 1.96
    4. 2.33
    5. 2.58
    6. The appropriate value is 2.58 from qnorm(.995)
z_star_99 <- qnorm(0.995)
z_star_99
## [1] 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 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)))
## `summarise()` ungrouping output (override with `.groups` argument)
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") 

  1. We would expect 99% of the intervals to contain the true population mean.
    1. True
    2. False
    3. The answer is True

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.