# How to compute a confidence interval for the difference between two means when both population variances are known (in R)

See all solutions.

If we have samples from two independent populations, and both of the population variances are known, how do we construct a confidence interval for the difference between the population means?

## Solution

We’re going to use some fake data here to illustrate how to make the confidence interval. Replace our fake data and population variances with your actual data and population variances if you use this code.

1
2
3
4
sample.1 <- c(15, 10, 7, 22, 17, 14)
sample.2 <- c(9, 1, 11, 13, 3, 6)
pop1.variance <- 2.3
pop2.variance <- 3


We will need the size and mean of each sample.

1
2
3
4
n.sample1 <- length(sample.1)
n.sample2 <- length(sample.2)
xbar1 <- mean(sample.1)
xbar2 <- mean(sample.2)


We can then use that data to create the confidence interval.

1
2
3
4
5
6
7
8
9
10
# Find the critical value from the normal distribution
alpha <- 0.05       # replace with your chosen alpha (here, a 95% confidence level)
critical.val <- qnorm(p=alpha/2, lower.tail=FALSE)

# Find the lower and upper bounds of the confidence interval
upper.bound <- (xbar1 - xbar2) + radius
lower.bound <- (xbar1 - xbar2) - radius
lower.bound
upper.bound

1
2
3
4
5
 5.157912

 8.842088


Our 95% confidence interval for the true difference between the population means is $[5.1579, 8.842]$.