If necessary, install the Mosaic package.

install.packages("mosaic")

Constructing a Confidence Interval for a Population Mean from Raw Data

Let’s construct a confidence interval for the population mean miles per gallon of a 2014 Toyota Camry. This follows Example 4 in Section 9.2. First, let’s enter the data in Table 3.

mpg <- c(25.9, 26.2, 32.5, 32.0, 27.2, 30.0, 25.5, 26.4, 27.4, 27.4, 27.0, 28.0, 31.2, 25.1, 30.6, 27.2)
Table3 <- data.frame("mpg"=mpg)   #Create a data frame and name column "mpg"
head(Table3,n=4)
##    mpg
## 1 25.9
## 2 26.2
## 3 32.5
## 4 32.0

Now, let’s construct the confidence interval.

library(mosaic)
t.test(~mpg,data=Table3,conf.level=0.95)
## 
##  One Sample t-test
## 
## data:  mpg
## t = 47.229, df = 15, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  26.83183 29.36817
## sample estimates:
## mean of x 
##      28.1

Note If you only want the confidence interval as the output, use the following command.

confint(t.test(~mpg,data=Table3,conf.level=0.95))
##   mean of x    lower    upper level
## 1      28.1 26.83183 29.36817  0.95

We are 95% confident the mean miles per gallon of a 2014 Toyota Camry is between 26.83 and 29.37.

Constructing a Confidence Interval for a Population Mean from Summarized Data

Suppose instead of raw data, you have summary statistics. Let’s use the mean of 28.1 and the standard deviation of 2.379916 (like the data from Table 3 where n = 16).

First, we need to install the BSDA package.

install.packages("BSDA")

Use the following command to construct the confidence interval:

tsum.test(mean.x = mean,s.x = standard deviation,n.x = sample size,conf.level=level of confidence)

library(BSDA)
tsum.test(mean.x = 28.1,s.x = 2.379916,n.x=16,conf.level=0.95)
## Warning in tsum.test(mean.x = 28.1, s.x = 2.379916, n.x = 16, conf.level =
## 0.95): argument 'var.equal' ignored for one-sample test.
## 
##  One-sample t-Test
## 
## data:  Summarized x
## t = 47.229, df = 15, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
##  26.83183 29.36817
## sample estimates:
## mean of x 
##      28.1

We are 95% confident the mean miles per gallon of a 2014 Toyota Camry is between 26.83 and 29.37.

Constructing a Confidence Interval for a Population Mean Using the Formula

We will use the data in Table 3.

library(mosaic)
xbar <- mean(~mpg,data=Table3)   # Find the mean
s <- sd(~mpg,data=Table3)        # Find the standard deviation
n <- length(mpg)                 # Find the number of observations
n
## [1] 16
se <- s/sqrt(n)                  # Compute standard error
se
## [1] 0.594979
E <- qt(0.975,df=n-1)*se         # Get critical value (assumes 95% level of confidence)
E
## [1] 1.268168
xbar + c(-E,E)                   # Construct confidence interval
## [1] 26.83183 29.36817