Confidence Intervals in R

In this post, I will show how one can easily construct confidence intervals in R. Assume you have a vector of numbers and you want to construct a confidence interval around the mean of this vector. The subsequent R code shows one easy way to calculate the confidence interval around the mean of this vector. The following code loads a function that allows you to pass on the vector and returns the confidence intervals. Per default the function returns the 95% confidence interval. However, the parameter ‘conf_level’ allows you to specify the interval you want.

#start with an empty workspace
#set seed

# load necessary packages for demo

# import the function from repository
url_robust <- ""
eval(parse(text = getURL(url_robust, ssl.verifypeer = FALSE)),

#generate a vector of random numbers
vector <- rnorm(100)

#calculate 95% confidence intervals

[1] -0.2580911  0.1966948

#calculate 90% confidence intervals
conf(vector,conf_level = 0.90)

[1] -0.2215323  0.1601360

Furthermore, if you do not have many observations, you may want to use Student’s t-distribution instead of the Normal distribution. The Student’s t-distribution has wider tales when the number of observations is low and gives a you more conservative estimates of your confidence interval. In case you want to use Student’s t-distribution you case set the parameter ‘distribution’, i.e. distribution=”normal”.

In case you do not know whether to use the Normal Distribution or the Student’s t-distribution , you might want to check out this post. In this post, I try illustrate the difference between using the Normal and the t-distribution.


One thought on “Confidence Intervals in R”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.