In this lab, we will make sure of the lattice and tidyverse packages.

library(lattice)
library(tidyverse)

We will also make use of the following helper function that generates summary statistics

favstats = function(mydata){
# input mydata is a numerical vector or matrices
result = rep(0, 9);
mysummary = summary(mydata);
result[1] = mysummary[1];
result[2] = mysummary[2];
result[3] = mysummary[3];
result[4] = mysummary[4];
result[5] = mysummary[5];
result[6] = mysummary[6];
result[7] = sd(mydata);
result[8] = length(mydata);
result[9] = sum(is.na(mydata));
names(result) = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n", "missing");
result;
}

## 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.

download.file("http://www.openintro.org/stat/data/ames.RData", destfile = "ames.RData")
load("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) Exercise 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. Exercise 2: Would you expect another student’s distribution to be identical to yours? Would you expect it to be similar? Why or why not? ## 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 $$\overline{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) 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. Exercise 3: 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? ## Confidence levels Exercise 4: What does “95% confidence” mean? If you’re not sure, see Section 4.2.2. 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) Exercise 5: 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? Exercise 6: 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. 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: • Obtain a random sample of size 60 • Calculate and store the sample’s summary statistics, in • Repeat steps (1) and (2) 50 times. • Use these stored statistics to calculate many confidence intervals. We can accomplish this using the replicate and favstats functions (recall that we first used these in Lab 6). The following lines of code takes a uniform random sample of size 60 from population, computes several summary statistics (including mean and sd), and then does this 100 times and saves the result as a data frame. samp = t(replicate(100, favstats(sample(population, size = 4)))) samp = data.frame(cbind(samp, rep(1, dim(samp)[1]), 1:dim(samp)[1])) names(samp) = c("min", "Q1", "median", "mean", "Q3", "max", "sd", "n", "missing", ".row", ".index") head(samp) ## min Q1 median mean Q3 max sd n missing .row .index ## 1 845 859.25 978.0 1099.00 1217.75 1595 349.1924 4 0 1 1 ## 2 1175 1426.25 1562.0 1482.75 1618.50 1632 212.0965 4 0 1 2 ## 3 904 975.25 1214.5 1211.50 1450.75 1513 304.6074 4 0 1 3 ## 4 1211 1418.75 1527.5 1614.50 1723.25 2192 414.1566 4 0 1 4 ## 5 747 780.75 1143.0 1133.00 1495.25 1499 420.1405 4 0 1 5 ## 6 1120 1461.25 1879.5 1836.25 2254.50 2466 605.1944 4 0 1 6 In the output, We see the first 6 rows of 50 rows of summary statistics. The $$i$$th row of samp stores summary statistcs of the $$i$$th sample. Each column of sampl is one kind of data summary, stord as a variable. From the output above, we can see the first column of samp is the minimum (min) of the 50 samples, the third column is the median median, etc. The sample mean is the 6th column and the sample sd is the 7th column. samp$lower = samp$mean - 1.96 * samp$sd / sqrt(60)
samp$upper = samp$mean + 1.96 * samp$sd / sqrt(60) The R codes above ask R to take the mean and sd stored in samp, and compute the lower and upper bound of the confidence interval. Lower bounds of these 50 confidence intervals are stored in lower, and the upper bounds are in upper. Let’s view the first interval. samp[1, c("lower", "upper")] ## lower upper ## 1 1010.642 1187.358 Let’s try to plot the 50 confidence intervals and see how many of them contain the true population mean using the plot_ci function below. Please first copy and paste the following R codes to the R console, and hit [Enter] to run them. panel.ci = function (x, y, mu, data2, ...) { panel.xyplot(x, y, ...) good = subset(data2, upper > mu & lower < mu) bad = subset(data2, upper < mu | lower > mu) with(good, panel.arrows(lower, .index, upper, .index, angle=90, length = 0.05, ends="both")) with(bad, panel.arrows(lower, .index, upper, .index, angle=90, length = 0.05, ends="both", col="red", lwd=3)) panel.abline(v=mu, lty=2) } plot_ci = function (df, mu, ...) { space = 0.1 * (max(df$upper) - min(df$lower)) xyplot(.index ~ mean, data=df, data2 = df, panel=panel.ci, mu = mu, xlim = c(min(df$lower) - space, max(df\$upper) + space), ylab = NULL)
}

And then we can plot our 50 confidence intervals using plot_ci as follows

plot_ci(samp, mu = mean(population))

In the above, we can see the 50 confidence intervals are plotted along with the true population mean marked by a vertical dash line. Those confidence intervals that miss the population are highlighted in red color.

Exercise 7: How many of your 50 confidence intervals include the true population mean? Is this proportion exactly equal to the confidence level 95%? If not, explain why.

• How will you modify the R codes above if you want to construct 90% confidence intervals instead of 95% confidence intervals? Calculate the 90% confidence intervals. You do not need to obtain new samples, simply calculate new intervals based on the 50 sample means and 50 SDs you have already calculated. Using the plot_ci function, plot all 90% intervals and calculate the proportion of intervals that include the true population mean. How does this percentage compare to 90%?