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
rm(list=ls())
#set seed
set.seed(2)
# load necessary packages for demo
library(RCurl)
# import the function from repository
url_robust <- "https://raw.githubusercontent.com/IsidoreBeautrelet/economictheoryblog/master/confidence_intervals.R"
eval(parse(text = getURL(url_robust, ssl.verifypeer = FALSE)),
envir=.GlobalEnv)
#generate a vector of random numbers
vector <- rnorm(100)
#calculate 95% confidence intervals
conf(vector)
[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.

### Like this:

Like Loading...

## One thought on “Confidence Intervals in R”