Confidence Intervals R Code Part 1

The following code produces confidence intervals in R using the normal distribution and confidence intervals using the t-distribution.

The code reproduces the figure 1 presented in this post.


#start with an empty workspace
rm(list=ls())

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)

##################################
## Compare confidence interval of 
## normal distribution with 
## t-distribution
##################################

intervals_normal <- NULL
for(nx in 2:100){
  interval <- conf_fix(0,10,nx)
  intervals_normal <- rbind(intervals_normal,interval)
}

intervals_t <- NULL
for(nx in 2:100){
  interval <- conf_fix(0,10,nx,distribution = "test")
  intervals_t <- rbind(intervals_t,interval)
}

png('comparison_confidence_intervals.png',width = 540, height = 540)
plot(intervals_normal[,1],type="l",ylim=c(-100,100),
     ylab="",xlab="Number of Observations",
     main="Confidence Intervals: Mean: 0, Std: 1")
lines(intervals_normal[,2])
lines(intervals_t[,1],col=2)
lines(intervals_t[,2],col=2)
legend("topright",c("Normal Distribution","t-Distribution"),
       lwd=c(1,1),col=c(1,2),bty = "n")
dev.off()

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

You are commenting using your Twitter 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.