Link: https://www.datacamp.com/courses/data-analysis-and-statistical-inference_mine-cetinkaya-rundel-by-datacamp/lab-3b-foundations-for-inference-confidence-intervals

Confidence intervals

load(url('http://s3.amazonaws.com/assets.datacamp.com/course/dasi/ames.RData'))
set.seed(123123)

In this part, we’ll translate that concept of reliability of mean estimates into something more tangible: confidence intervals.

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.

In this second part of the 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)

# Calculate the mean:
sample_mean = mean(samp)
sample_mean
## [1] 1495
# Draw a histogram:
hist(samp)

plot of chunk unnamed-chunk-2

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

TRUE

Confidence intervals

Now let’s 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 x bar (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.

se = sd(samp) / sqrt(60)
lower = sample_mean - 1.96 * se
upper = sample_mean + 1.96 * se
c(lower, upper)
## [1] 1377 1614

It is an important inference that we make with this: 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.

se = sd(samp) / sqrt(60)

ci = sample_mean + c(-1.96, +1.96) * se
ci
## [1] 1377 1614
lower = ci[1]
upper = ci[2]

Great! There are a few conditions that need to be met for this interval to be valid.

What are these conditions?

  • independent observations
  • sufficiently large sample
  • no skews

For the confidence interval to be valid, the sample mean must be normally distributed and have standard error \(\cfrac{s}{\sqrt{n}}\). Which of the following is not a condition needed for this to be true?

  • The sample is random.
  • The sample size, 60, is less than 10% of all houses.
  • The sample distribution must be nearly normal.

The sample distribution must be nearly normal. the sample size is sufficiently large for that

What does “95% confidence” mean?

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

Tip: Check if your confidence interval c(lower, upper) captures the true average size of houses in Ames!

mean(population)
## [1] 1500
c(lower, upper)
## [1] 1377 1614

What proportion of 95% confidence intervals would you expect to capture the true population mean? > 95%

Challenge

Using R, we’re going to recreate many samples using a for loop. Here is the rough outline:

  1. Obtain a random sample.
  2. Calculate the sample’s mean and standard deviation.
  3. Use these statistics to calculate a confidence interval.
  4. Repeat steps (1)-(3) 50 times.
  5. Construct 95% Confidence Intervals and plot them
plot_ci = function(lo, hi, m) {
  par(mar=c(2, 1, 1, 1), mgp=c(2.7, 0.7, 0))
  k <- 50
  ci.max <- max(rowSums(matrix(c(-1 * lo, hi), ncol=2)))

  xR <- m + ci.max * c(-1, 1)
  yR <- c(0, 41 * k / 40)

  plot(xR, yR, type='n', xlab='', ylab='', axes=FALSE)
  abline(v=m, lty=2, col='#00000088')
  axis(1, at=m, paste("mu = ", round(m, 4)), cex.axis=1.15)

  for(i in 1:k) {
    x  <- mean(c(hi[i], lo[i]))
    ci <- c(lo[i], hi[i])
    if (contains(lo[i], hi[i], m) == FALSE) {
      col <- "#F05133"
      points(x, i, cex=1.4, col=col)
      lines(ci, rep(i, 2), col=col, lwd=5)
    }
    col <- 1
    points(x, i, pch=20, cex=1.2, col=col)
    lines(ci, rep(i, 2), col=col)
  }
}
samp_mean = rep(NA, 50)
samp_sd = rep(NA, 50)
n = 60

for (i in 1:50) {
    samp = sample(population, n)
    samp_mean[i] = mean(samp)
    samp_sd[i] = sd(samp)
}

# Calculate the interval bounds here:
lower = samp_mean - 1.96 * samp_sd / sqrt(n)
upper = samp_mean + 1.96 * samp_sd / sqrt(n)

# Plotting the confidence intervals:
pop_mean = mean(population)
plot_ci(lower, upper, pop_mean)

plot of chunk unnamed-chunk-7

The 99%

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. Using the plot_ci function, plot all intervals and calculate the proportion of intervals that include the true population mean.

What is the appropriate critical value for a 99% confidence level?

cl = 0.99
alpha = (1 - cl) / 2
qnorm(alpha, lower.tail=F)
## [1] 2.576

2.58

samp_mean = rep(NA, 50)
samp_sd = rep(NA, 50)
n = 60

for (i in 1:50) {
  samp = sample(population, n)
  samp_mean[i] = mean(samp)
  samp_sd[i] = sd(samp)
}

# Calculate the interval bounds here:
lower = samp_mean - 2.58 * samp_sd / sqrt(n)
upper = samp_mean + 2.58 * samp_sd / sqrt(n)

# Plotting the confidence intervals:
pop_mean = mean(population)
plot_ci(lower, upper, pop_mean)

plot of chunk unnamed-chunk-9