# ECON 103 - Summer 2016
# R code for past question, end of Lecture 15
# Fall 2014 Midterm II Q3
remove(list=ls())
rm(list=ls(all=TRUE))
# First let's look at a simple example of how we build our own functions, from R tutorial 3:
mymean <- function(x){
x <- x[!is.na(x)]
x.bar <- sum(x)/length(x)
return(x.bar)
}
# You should always test your function to make sure it is doing what we want
x = c(1,2,3,97,98,99,NA);
mymean(x)
# Good, this gives the answer we're looking for
# Now let's look at the past midterm question
## Question: Write an R function called CI.normal.mean that constructs a 90% confi-
## dence interval for the mean of a normal population with known population variance.
## Your function should take two arguments: x is a vector of sample data, assumed to be
## a sequence of iid draws from a normal population, and s is the population standard
## deviation, assumed known. Your function should return a vector with two elements: the
## first is the lower confidence limit and the second is the upper confidence limit.
CI.normal.mean <- function(x, s){
n <- length(x)
ME <- qnorm(0.95) * s / sqrt(n)
LCL <- mean(x) - ME
UCL <- mean(x) + ME
return(c(LCL, UCL))
}
# Let's test our function
# First, we need to generate some data to use an input
# Following the lectures, I will generate data from a normal distribution using rnorm
# If we forget how to use rnorm, we can look up the help file by doing:
?rnorm
# When we generate random variables, we can set the seed so our results are reproducible
# x2 and x3 will be the same, but x4 will be different
set.seed(10)
x2 = rnorm(100,mean = 5, sd = 4)
set.seed(10)
x3 = rnorm(100,mean = 5, sd = 4)
x4 = rnorm(100,mean = 5, sd = 4)
# Let's see what our data looks like
hist(x2)
# Now let's test our function, using the fact that we know that the 'true' s is 4
CI.normal.mean(x2,4)
# This gives us a 95% CI that contains the true mean, 5, which looks pretty good!