# R-program for Supplementary Exercises 6.13 and 6.14 of IPS7e # R does not have a built-in function for this model because it is unrealistic in practice # - this solution shows 3 different approaches to do the analysis anyway... corn <- read.csv("r:/Chapter 6/ex06_013.csv") # method 1: manual calculation using formulae mean <- mean(corn$Yield) n <- length(corn$Yield) sd <- 10 se <- sd/sqrt(n) # 90% CI: lower <- mean-qnorm(0.95)*se; upper <- mean+qnorm(0.95)*se; as.vector(c(lower,upper)) # 95% CI: lower <- mean-qnorm(0.975)*se; upper <- mean+qnorm(0.975)*se; as.vector(c(lower,upper)) # 99% CI: lower <- mean-qnorm(0.995)*se; upper <- mean+qnorm(0.995)*se; as.vector(c(lower,upper)) # 95% CI for hypothetical sample of size 50 with mean 123.8 lower <- 123.8-qnorm(0.975)*sd/sqrt(50); upper <- 123.8+qnorm(0.975)*sd/sqrt(50) as.vector(c(lower,upper)) # method 2: write a function to do the calculation # based on: http://www.r-bloggers.com/one-sample-z-test/ z.ci = function(a, sd, conf.level=0.95){ lower = mean(a) - qnorm(1-(1-conf.level)/2)*sd/sqrt(length(a)) upper = mean(a) + qnorm(1-(1-conf.level)/2)*sd/sqrt(length(a)) return(as.vector(c(lower,upper))) } z.ci(corn$Yield, sd=10, conf.level=0.90) z.ci(corn$Yield, sd=10, conf.level=0.95) z.ci(corn$Yield, sd=10, conf.level=0.99) z.ci(c(123.8), sd=10/sqrt(50), conf.level=0.95) # last calculation forges a sample size of 50 by dividing the sd by sqrt(50) # method 3: using add-on library TeachingDemos # note: it is not always a good idea to just use some add-on library... # ignore the z-test and use only the CI library(TeachingDemos) z.test(corn$Yield, sd=10, conf.level=0.90) z.test(corn$Yield, sd=10, conf.level=0.95) z.test(corn$Yield, sd=10, conf.level=0.99) z.test(c(123.80), sd=10/sqrt(50), conf.level=0.95) # same trick as above for last calculation