##########################################################################
# 統計學 (一)                                                            #
# Anderson et al., Statistics for Business & Economics (14th Edition)    #
# Chapter 8: Interval Estimation                                         #
# 吳漢銘 國立政治大學統計學系                                            #
# http://www.hmwu.idv.tw/                                                #
##########################################################################



######################################
# 8.1 Population Mean: sigma Known   #
######################################

# X1, X2, ..., Xn ~ N(mu, sigma^2), 100*(1-alpha)% CI for mu
n <- 100
xbar <- 82
sigma <- 20 # sigma Known

sigma.xbar <- sigma/sqrt(n)
sigma.xbar 
alpha <- 0.05  # 95% significance level
qnorm(alpha/2)
z.alpha <- qnorm(1 - alpha/2)
z.alpha

# Margin of Error 
margin.error <- z.alpha * sigma.xbar
c(-margin.error, margin.error)

# 100(1 - alpha)%  confidence coefficient for population mean
c(xbar - margin.error, xbar + margin.error)


# Chapter 7: Lloyd’s example
# (a) Each week Lloyd’s Department Store selects a simple random sample of 100
#     customers in order to learn about the amount spent per shopping trip.
# (b) With x representing the amount spent per shopping trip, the sample mean ¯x
#     provides a point estimate of μ, the mean amount spent per shopping trip
#     for the population of all Lloyd’s customers.
# (c) Based on the historical data, Lloyd’s now assumes a known value of sigma = $20
#     for the population standard deviation and the population follows a normal
#     distribution.

# if you read excel 
# library(readxl)
LloydS <- read_excel("data/chap08/LloydS.xlsx")

# if you read csv
# LloydS <- read.csv("data/chap08/LloydS.csv")
# str(LloydS)
# LloydS$"Amount Spent" <- LloydS$Amount.Spent

str(LloydS)
head(LloydS)
tail(LloydS)
N <- length(LloydS$"Amount Spent")
N
n <- 30
id <- sample(1:N, n)
xbar <- mean(LloydS$"Amount Spent"[id])
sigma.xbar <- 20/sqrt(n)
sigma.xbar 
alpha <- 0.05  # 95% significance level
qnorm(alpha/2)
z.alpha <- qnorm(1 - alpha/2)
z.alpha 
margin.error <- z.alpha * sigma.xbar
c(xbar - margin.error, xbar + margin.error)



# suppose true mean mu = mean(LloydS$"Amount Spent")
count <- numeric(15000)
mu <- mean(LloydS$"Amount Spent")
mu
n <- 30
alpha <- 0.05  # 95% significance level
z.alpha <- qnorm(1 - alpha/2)

for(i in 1:15000){
 xbar <- mean(LloydS$"Amount Spent"[sample(1:N, n)])
 sigma.xbar <- sigma/sqrt(n)
 margin.error <- z.alpha * sigma.xbar
 lower <- xbar - margin.error
 upper <- xbar + margin.error
 if(lower <= mu & mu <= upper) count[i] <- 1
}
mean(count)


########################################
# 8.2 Population Mean: sigma unknown   #
########################################

# dt(x, df, ncp, log = FALSE)
# pt(q, df, ncp, lower.tail = TRUE, log.p = FALSE)
# qt(p, df, ncp, lower.tail = TRUE, log.p = FALSE)
# rt(n, df, ncp)


dt(x = 1.812, df = 10)

pt(q = 1.812, df = 10)

qt(p = 0.05, df =10)
qt(p = 1- 0.05, df =10)
qt(p = 0.05, df =10, lower.tail = FALSE)

rt(5, df =10)
        
# (1-alpha)100% CI for mu: sigma unknown
# xbar +- margin of error
# margin of error: E = t(alpha, df) * s/sqrt(n)


# Example:
# Compute an interval estimate of the population mean credit card balance for the population of U.S. households. 
# n = 70
# sigma is unknown

NewBalance <- read_excel("data/chap08/NewBalance.xlsx")
head(NewBalance)
str(NewBalance)
n <- length(NewBalance$NewBalance)
alpha <- 0.05
xbar <- mean(NewBalance$NewBalance)
s <- sd(NewBalance$NewBalance)
E <- qt(1-alpha/2, df = n -1) * s/sqrt(n)
round(c(xbar - E, xbar + E))


# Example
#Training Time In Days for a Sample of 20 Scheer Industries Employees
Scheer <- read_excel("data/chap08/Scheer.xlsx")
head(Scheer)
str(Scheer)
hist(Scheer$Days, main = "Histogram of Training Times for the Scheer Industries Sample")

n <- length(Scheer$Days)
alpha <- 0.05
xbar <- mean(Scheer$Days)
s <- sd(Scheer$Days)
E <- qt(1-alpha/2, df = n -1) * s/sqrt(n)
round(c(xbar - E, xbar + E), 1)




########################################
# 8.3 Determining the sample size      #
########################################
# Sample Size For An Interval Estimate Of A Population Mean
# n = (Z_{alpha/2}^2 * sigma^2)/E^2


# Example
# investigated the cost of renting automobiles in the United States 
#    found a mean cost of approximately $55 per day for renting a 
#    midsize automobile. 
# E = $2 and a 95% level of confidence.
# Compute the sample size for the new study needs, using 9.65 as the planning value for s 

margin.error <- 2
alpha <- 0.05
z.alpha <- qnorm(1-alpha/2)
sigma <- 9.65

ceiling((z.alpha^2 * sigma^2)/ margin.error^2)



########################################
# 8.4 Population Proportion            #
########################################
# Interval Estimate Of A Population Proportion
# p.bar +- Margin of Error
# Margin of Error = {z_alpha/2} sqrt(p.bar * (1-p.bar)/n)


# Example:
# A national survey of 900 women golfers was conducted to learn how 
#    women golfers view their treatment at golf courses in the 
#    United States. The survey found that 396 of the women golfers 
#    were satisfied with the availability of tee times. 

# Compute the point estimate of the proportion of the population of women golfers who are satisfied with the availability of tee times
# Compute a 95% confidence level for mu

n <- 900
x <- 396
p.bar <- x/n
p.bar


z.value <- qnorm(1-alpha/2)
E <- z.value * sqrt(p.bar * (1-p.bar)/n)
E
c(p.bar - E, p.bar + E)


#  Determining the Sample Size
#  n = ((z_{alpha/2}^2) * pbar * (1-pbar))/E^2

# How large should the sample be if the survey director wants to 
#    estimate the population proportion with a 
#    margin of error of .025 at 95% confidence? 
# Using the previous survey result of p = 0.44 as the planning value p*
        
p.bar <- 0.44
E <- 0.025
alpha <- 0.05
z <- qnorm(1-alpha/2)
n <- (z^2 * p.bar * (1-p.bar))/E^2
ceiling(n)

# selecting a planning value p* is to use p* = .50.

p.bar <- 0.5
n <- (z^2 * p.bar * (1-p.bar))/E^2
ceiling(n)





