How to Calculate Confidence Interval in R

We’re going to walk through how to calculate confidence interval in R. There are a couple of ways this problem can be presented to us….

Calculate Confidence Interval in R – Normal Distribution

Given the parameters of the distribution, generate the confidence interval. In this situation, we’re basically using r like a calculator…

# Calculate Confidence Interval in R for Normal Distribution
# Assume mean of 12
# Standard deviation of 3
# Sample size of 30
# 95% confidence interval so tails are .925

> center <- 12
> stddev <- 3
> n <- 30
> error <- qnorm(0.975)*stddev/sqrt(n)
> error
[1] 1.073516
> lower_bound <- center - error
> lower_bound
[1] 10.92648
> upper_bound <- center + error
> upper_bound
[1] 13.07352

Thus the range in this case is between 10.9 and 13.1 (rounding outwards).

Calculate Confidence Interval in R – t Distribution

For experiments run with smaller sample sizes it is generally inappropriate to use the normal distribution. Student’s t distribution is the correct choice for this environment.

R can support this by substituting the qt function for the qnorm function, as demonstrated below…. assume we are working with a sample size of 15. You will need to tell the qt function the degrees of freedom as a parameter (should be n-1).

# Calculate Confidence Interval in R for t Distribution
# Assume mean of 12
# Standard deviation of 3
# Sample size of 15
# 95% confidence interval so tails are .925

> center <- 12
> stddev <- 3
> n <- 30
> error <- qt(0.975, df=n-1)*stddev/sqrt(n)
> error
[1] 1.661345
> lower_bound <- center - error
> lower_bound
[1] 10.33866
> upper_bound <- center + error
> upper_bound
[1] 13.66134

As expected, the confidence interval widens…

Related Materials