(1)(a) (6 points) The Poisson distribution may be used to approximate the binomial distribution if n > 20 and np < 7. Estimate the following binomial probabilities using dpois() and ppois() with probability p = 0.05, and n = 100. Then, estimate the same probabilities using dbinom() and pbinom(). Show the numerical results of your calculations.
p = .05
n = 100
lambda = n * p
x = 0
s = sprintf("dpois: %.5f vs dbinom: %.5f\n", dpois(x, lambda), dbinom(x, n, p))
s = paste0(s, sprintf("ppois: %.5f vs pbinom: %.5f", ppois(x, lambda), pbinom(x, n, p)))
cat(s)
## dpois: 0.00674 vs dbinom: 0.00592
## ppois: 0.00674 vs pbinom: 0.00592
x = 5
s = sprintf("dpois: %.5f vs dbinom: %.5f\n", sum(dpois(0:x, lambda)), sum(dbinom(0:x, n, p)))
s = paste0(s, sprintf("ppois: %.5f vs pbinom: %.5f", ppois(x, lambda), pbinom(x, n, p)))
cat(s)
## dpois: 0.61596 vs dbinom: 0.61600
## ppois: 0.61596 vs pbinom: 0.61600
(1)(b) (3 points) Generate side-by-side barplots using par(mfrow = c(1,2)) or grid.arrange(). The left barplot will show Poisson probabilties for outcomes ranging from 0 to 10. The right barplot will show binomial probabilities for outcomes ranging from 0 to 10. Use p = 0.05 and n = 100. Title each plot, present in color and assign names to the bar; i.e. x-axis value labels.
x <- 0:10
dp <- dpois(x,lambda = 5)
db <- dbinom(x, n, p)
par(mfrow=c(1,2))
barplot(dp, main ="Poisson Distribution", col="aquamarine2", xlab = "Outcome", ylab ="Probability")
barplot(db, main = "Binomial Distribution", col = "violet", xlab = "Outcome", ylab = "Probability")
(1)(c) For this problem, refer to Sections 5.2 of Business Statistics. A discrete random variable has outcomes: 0, 1, 2, 3, 4, 5, 6. The corresponding probabilities in sequence with the outcomes are: 0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001. In other words, the probabilty of obtaining “0” is 0.215.
x <- c(0, 1, 2, 3, 4, 5, 6)
p.x <- c(0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001)
mu <- sum(x * p.x)
x.var <- sum((x - mu)^2 * p.x)
s = sprintf("For this distribution\n\nThe expected value is: %.2f\nThe variance is : %.2f", mu, x.var)
cat(s)
## For this distribution
##
## The expected value is: 1.80
## The variance is : 1.79
sum(p.x)
## [1] 1.001
cump <- cumsum(p.x)
# Median class is the third class as the third class spread through 0.5
# Determine Median value
N = sum(x)
L = x[3-1]
med.freq = .5
med = L + (.5 - sum(p.x[1:2]))/p.x[3]
plot(x, cump, col="aquamarine3", main = "Outcomes vs Cum. Prob.",
xlab="outcomes", ylab="Cum. prob.",
ylim=c(0, 1),
bty="n", lwd=2)
abline(h=med.freq, col="orange", lty=2, lwd=1)
abline(v=med, col="orange", lty=2, lwd=1)
points(med, med.freq, col="steelblue", cex=1.2, pch=4)
text(med, med.freq, sprintf("Median = %.2f", med),
cex=1., pos=3, col="violet")
(2)(a) (3 points) Load the “faithful” dataset and present summary statistics and a histogram of waiting times.
data(faithful)
summary(faithful)
## eruptions waiting
## Min. :1.600 Min. :43.0
## 1st Qu.:2.163 1st Qu.:58.0
## Median :4.000 Median :76.0
## Mean :3.488 Mean :70.9
## 3rd Qu.:4.454 3rd Qu.:82.0
## Max. :5.100 Max. :96.0
colors = c("yellow", "aquamarine", "steelblue2", "violet", "pink", "cyan", "orange")
hist(faithful$waiting, main = "Histogram of Old Faithful geyser eruption wait time",
xlab = "Wait Time", col=colors)
Additionally, compute the empirical conditional probability of an eruption less than 3.0 minutes, if the waiting time exceeds 70 minutes.
wait70 <- subset(faithful, waiting > 70)
erupt3 <- subset(wait70, eruptions < 3)
s = sprintf("The empirical conditional probability of an eruption less than 3.0 minutes, if the waiting time exceeds 70 minutes is:\n%.5f", nrow(erupt3)/nrow(wait70))
cat(s)
## The empirical conditional probability of an eruption less than 3.0 minutes, if the waiting time exceeds 70 minutes is:
## 0.00606
df = subset(subset(faithful, waiting != erupt3$waiting), eruptions != erupt3$waiting)
plot(df$waiting, df$eruptions, col="aquamarine3", main = "Faithful Observations",
xlab="Waiting Time", ylab="Eruption Time",
bty="n", lwd=1)
abline(h=3, col="violet", lty=2, lwd=1)
abline(v=70, col="violet", lty=2, lwd=1)
points(erupt3$waiting, erupt3$eruptions, col="red", cex=1, pch = 2)
Answer: There’s a postive correlation between eruption and wait time. (Which makes perfect sense physically) In other words, the longer you wait, the longer of a eruption you’ll see.
(2)(b) (4.5 points) Past research indicates that the waiting times between consecutive eruptions are not independent. This problem will check to see if there is evidence of this. Form consecutive pairs of waiting times. In other words, pair the first and second waiting times, pair the third and fourth waiting times, and so forth. There are 136 resulting consecutive pairs of waiting times. Form a data frame with the first column containing the first waiting time in a pair and the second column with the second waiting time in a pair. Plot the pairs with the second member of a pair on the vertical axis and the first member on the horizontal axis.
One way to do this is to pass the vector of waiting times - faithful$waiting - to matrix(), specifying 2 columns for our matrix, with values organized by row; i.e. byrow = TRUE.
mwait <- matrix(faithful$waiting, ncol=2, byrow=TRUE)
plot(x = mwait[, 1], y = mwait[, 2], col="violet", main = "Faithful Observations",
xlab="First Column", ylab="Second Column",
bty="n", lwd=1)
(2)(c) (2) Test the hypothesis of independence with a two-sided test at the 5% level using the Kendall correlation coefficient.
library(Kendall)
cor.test(mwait[,1],mwait[,2],alternative = "two.sided",method = "kendall", conf.level = 0.95)
##
## Kendall's rank correlation tau
##
## data: mwait[, 1] and mwait[, 2]
## z = -4.9482, p-value = 7.489e-07
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
## tau
## -0.2935579
Null hypothesis = data are not independent; we reject the Null hypothesis, therefore based on the data we have we think the waiting times between consecutive eruptions are independent.
# load "ChickWeight" dataset
data(ChickWeight)
# Create T | F vector indicating observations with Time == 21 and Diet == "1" OR "3"
index <- ChickWeight$Time == 21 & (ChickWeight$Diet == "1" | ChickWeight$Diet == "3")
# Create data frame, "result," with the weight and Diet of those observations with "TRUE" "index"" values
result <- subset(ChickWeight[index, ], select = c(weight, Diet))
# Encode "Diet" as a factor
result$Diet <- factor(result$Diet)
str(result)
## Classes 'nfnGroupedData', 'nfGroupedData', 'groupedData' and 'data.frame': 26 obs. of 2 variables:
## $ weight: num 205 215 202 157 223 157 305 98 124 175 ...
## $ Diet : Factor w/ 2 levels "1","3": 1 1 1 1 1 1 1 1 1 1 ...
(3)(a) (3 points) Display two side-by-side vertical boxplots using par(mfrow = c(1,2)). One boxplot would display diet “1” and the other diet “3”.
result1 <- subset(result, Diet == "1")
result3 <- subset(result, Diet == "3")
par(mfrow=c(1,2))
boxplot(result1$weight, col = "steelblue", range = 1.5, main = "Diet 1",
ylab = "Chick Weight", notch = TRUE, frame=F)
boxplot(result3$weight, col = "steelblue", range = 1.5, main = "Diet 3",
ylab = "Chick Weight", notch = TRUE, frame=F)
## Warning in bxp(list(stats = structure(c(147, 220, 281, 321, 373), .Dim = c(5L, :
## some notches went outside hinges ('box'): maybe set notch=FALSE
(3)(b) (3 points) Use the “weight” data for the two diets to test the null hypothesis of equal population mean weights for the two diets. Test at the 95% confidence level with a two-sided t-test. This can be done using t.test() in R. Assume equal variances. Display the results of t.test().
t.test(result1$weight, result3$weight, alternative = "two.sided", conf.level = 0.95)
##
## Welch Two Sample t-test
##
## data: result1$weight and result3$weight
## t = -3.4293, df = 16.408, p-value = 0.003337
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -149.64644 -35.45356
## sample estimates:
## mean of x mean of y
## 177.75 270.30
# load "ChickWeight" dataset
data(ChickWeight)
# Create T | F vector indicating observations with Diet == "3"
index <- ChickWeight$Diet == "3"
# Create vector of "weight" for observations where Diet == "3" and Time == 20
pre <- subset(ChickWeight[index, ], Time == 20, select = weight)$weight
# Create vector of "weight" for observations where Diet == "3" and Time == 21
post <- subset(ChickWeight[index, ], Time == 21, select = weight)$weight
# The pre and post values are paired, each pair corresponding to an individual chick.
cbind(pre, post)
## pre post
## [1,] 235 256
## [2,] 291 305
## [3,] 156 147
## [4,] 327 341
## [5,] 361 373
## [6,] 225 220
## [7,] 169 178
## [8,] 280 290
## [9,] 250 272
## [10,] 295 321
(3)(c) (3 points) Present a scatterplot of the variable “post” as a function of the variable “pre”. Include a diagonal line with zero intercept and slope equal to one. Title and label the variables in this scatterplot.
plot(pre, post, col="violet", main = "Post ~ Pre",
xlab="Pre", ylab="Post",
bty="n", lwd=1)
abline(0, 1, col='steelblue')
(3)(d) (6 points) Calculate and present a one-sided, 95% confidence interval for the average weight gain from day 20 to day 21. Write the code for the paired t-test and for determination of the confidence interval endpoints. **Do not use *t.test()**, although you may check your answers using this function. Present the resulting test statistic value, critical value, p-value and confidence interval.
\(D =\) mean population difference (pre - post)
\(H_0:D=0\)
\(H_a:D<0\)
ci = .95
x = pre
y = post
n = length(x)
d = x - y
D = 0
dbar = mean(d)
df = n - 1
sd = ( sum((d-dbar)^2) / df )^.5 # or just use sd(d)
t = (dbar - D) / (sd/n^.5)
cv = qt((1-ci)/2, df)
margin.err <- cv * sd / n^.5
ci0 <- dbar + margin.err
ci1 <- dbar - margin.err
p = pt(t, df)
s <- sprintf("\n Paired t-test\n\ndata: pre and post\n")
s <- paste0(s, sprintf("t = %.4f, df = %d, p-value = %.4f\n", t, df, p))
s <- paste0(s, sprintf("alternative hypothesis: true difference in means is not equal to 0\n"))
s <- paste0(s, sprintf("%d percent confidence interval:\n", ci*100))
s <- paste0(s, sprintf(" %.4f %.4f\n", ci0, ci1))
s <- paste0(s, sprintf("sample estimates:\nmean of the differences\n"))
s <- paste0(s, sprintf(" %.1f\n", dbar))
s <- paste0(s, sprintf("\nCritical Value:\n %.4f %.4f\n", cv, -cv))
cat(s)
##
## Paired t-test
##
## data: pre and post
## t = -3.2253, df = 9, p-value = 0.0052
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -19.3958 -3.4042
## sample estimates:
## mean of the differences
## -11.4
##
## Critical Value:
## -2.2622 2.2622
data(Nile)
m <- mean(Nile)
std <- sd(Nile)
x <- seq(from = 400, to = 1400, by = 1)
hist(Nile, freq = FALSE, col = "darkblue", xlab = "Flow",
main = "Histogram of Nile River Flows, 1871 to 1970")
curve(dnorm(x, mean = m, sd = std), col = "orange", lwd = 2, add = TRUE)
(4)(a) (3 points) Using Nile River flow data and the “moments” package, calculate skewness and kurtosis.
library(moments)
s = sprintf("Nile River Flows, 1871 to 1970 data\n\n")
s = paste0(s, sprintf("skewness: %.4f\nkurtosis: %.4f", skewness(Nile), kurtosis(Nile)))
cat(s)
## Nile River Flows, 1871 to 1970 data
##
## skewness: 0.3224
## kurtosis: 2.6951
Present a QQ plot and boxplot of the flow data side-by-side using qqnorm(), qqline() and boxplot(); par(mfrow = c(1, 2)) may be used to locate the plots side-by-side. Add features to these displays as you choose.
par(mfrow = c(1, 2))
qqnorm(Nile, pch=2, col="violet", frame=FALSE, main = "Normal Q-Q Plot (Nile)")
qqline(Nile, col = "steelblue", lwd = 2)
boxplot(Nile, col = "steelblue", range = 1.5, main = "Nile River Flow",
ylab = "Flow", notch = TRUE, frame=F)
(4)(b) (6 points) Using set.seed(124) and the Nile data, generate 1000 random samples of size n = 16, with replacement. For each sample drawn, calculate and store the sample mean. This can be done with a for-loop and use of the sample() function. Label the resulting 1000 mean values as “sample1”. Repeat these steps using set.seed(127) - a different “seed” - and samples of size n = 64. Label these 1000 mean values as “sample2”. Compute and present the means, sample standard deviations and sample variances for “sample1” and “sample2” in a table with the first row for “sample1”, the second row for “sample2” and the columns labled for each statistic.
sp.wly <- function(cnt, n, seed = 124, data = Nile, replace = TRUE){
set.seed(seed)
return( replicate(cnt, mean(sample(data, n, replace = TRUE))) )
}
sample1 <- sp.wly(1000, 16, seed = 124)
sample2 <- sp.wly(1000, 64, seed = 127)
sp.stat <- function(sp){ # sp for sample
return( c(mean(sp), sd(sp), var(sp)) )
}
row_names <- c("Sample1","Sample2")
col_names <- c("Mean","Sample std dev","Sample variance")
matrix(c(sp.stat(sample1), sp.stat(sample2)), nrow = 2, ncol = 3, byrow = TRUE,
dimnames = list(row_names, col_names))
## Mean Sample std dev Sample variance
## Sample1 918.7364 42.00156 1764.1312
## Sample2 918.5149 20.22883 409.2054
(4)(c) (6 points) Present side-by-side histograms of “sample1” and “sample2” with the normal density curve superimposed. To prepare comparable histograms, it will be necessary to use “freq = FALSE” and to maintain the same x-axis with “xlim = c(750, 1050)”, and the same y-axis with “ylim = c(0, 0.025).” To superimpose separate density functions, you will need to use the mean and standard deviation for each “sample” - each histogram - separately.
par(mfrow = c(1, 2))
x.lim <- c(750, 1040)
y.lim <- c(0, 0.025)
m = mean(sample1)
std = sd(sample1)
hist(sample1, freq = FALSE, col = "aquamarine", xlab = "Flow", main = "Sample 1",
xlim = x.lim,ylim = y.lim)
curve(dnorm(x, mean = m, sd = std), col = "violet", lwd = 2, add = TRUE)
m = mean(sample2)
std = sd(sample2)
hist(sample2, freq = FALSE, col = "aquamarine", xlab = "Flow", main = "Sample 2",
xlim = x.lim,ylim = y.lim)
curve(dnorm(x, mean = m, sd = std), col = "violet", lwd = 2, add = TRUE)
(5)(a)(4.5 points) warpbreaks is part of the “datasets” package and may be loaded via data(warpbreaks). Load “warpbreaks” and present the structure using str().
data(warpbreaks)
str(warpbreaks)
## 'data.frame': 54 obs. of 3 variables:
## $ breaks : num 26 30 54 25 70 52 51 26 67 18 ...
## $ wool : Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
## $ tension: Factor w/ 3 levels "L","M","H": 1 1 1 1 1 1 1 1 1 2 ...
Calculate the median number of breaks for the entire dataset, disregarding “tension” and “wool”. Define this median value as “median_breaks”. Present a histogram of the number of breaks with the location of the median indicated.
median_breaks <- median(warpbreaks$breaks)
hist(warpbreaks$breaks, main = "Histogram of warpbreaks",
xlab = "Number of Breaks", col=colors)
abline(v=median_breaks, col="violet", lty=2, lwd=2)
Create a new variable “number” as follows: for each value of “breaks”, classify the number of breaks as either strictly below “median_breaks”, or the alternative. Convert the “above”|“below” classifications to a factor, and combine with the dataset warpbreaks.
number <- as.factor(ifelse(warpbreaks$breaks<median_breaks, "below", "above"))
warpbreaks2 <- cbind(warpbreaks,number)
Present a summary of the augmented dataset using summary().
summary(warpbreaks2)
## breaks wool tension number
## Min. :10.00 A:27 L:18 above:29
## 1st Qu.:18.25 B:27 M:18 below:25
## Median :26.00 H:18
## Mean :28.15
## 3rd Qu.:34.00
## Max. :70.00
Present a contingency table of the frequency of breaks using the two variables “tension” and “number”. There should be six cells in this table.
tbl <- table(warpbreaks2$tension, warpbreaks2$number)
tbl
##
## above below
## L 14 4
## M 10 8
## H 5 13
(5)(b)(3 points) Using the table constructed in (5)(a), test at the 5% level the null hypothesis of independence using the uncorrected chisq.test() (Black, Business Statistics, Section 16.2). Show the results of this test and state your conclusions.
chisq.test(tbl)
##
## Pearson's Chi-squared test
##
## data: tbl
## X-squared = 9.0869, df = 2, p-value = 0.01064
At \(\alpha=.05\), p value .01064 is significantly smaller than \(\alpha\), therefore we reject the Null hypothesis and we think it is statistically significant that tension and number are not independent.
(5)(c) (7.5 points) Write a function that computes the uncorrected Pearson Chi-squared statistic. Apply your function to the table from (5)(a). You should be able to duplicate the X-squared value (chi-squared) and p-value. Present both.
Shown below are examples of the type of function required. These examples will have to be modified to accomodate the table generated in (5)(a).
Modified version of Function 1
chi <- function(x) {
# To be used with 3x2 contingency tables that have margins added.
# Expected values are calculated.
e11 <- x[4,1]*x[1,3]/x[4,3]
e12 <- x[4,2]*x[1,3]/x[4,3]
e21 <- x[4,1]*x[2,3]/x[4,3]
e22 <- x[4,2]*x[2,3]/x[4,3]
e31 <- x[4,1]*x[3,3]/x[4,3]
e32 <- x[4,2]*x[3,3]/x[4,3]
df = 2
# Value of chi square statistic is calculated.
chisqStat <- (x[1,1] - e11)^2/e11 + (x[1,2] - e12)^2/e12 + (x[2,1] - e21)^2/e21 +
(x[2,2] - e22)^2/e22 + (x[3,1] - e31)^2/e31 + (x[3,2] - e32)^2/e32
s = sprintf("Pearson's Chi-squared test\nChi sq = %.4f , df = %d , P-value = %.5f", chisqStat, df,
pchisq(chisqStat, df, lower.tail = F))
cat(s)
}
x<-addmargins(tbl)
chi(x)
## Pearson's Chi-squared test
## Chi sq = 9.0869 , df = 2 , P-value = 0.01064
Modified version of Function 2
chisqfun <- function(t) {
x <- addmargins(t)
e <- array(numeric(), dim(t))
a <- nrow(t)
b <- ncol(t)
for (i in 1:a) {
for (j in 1:b) {
e[i, j] = x[nrow(x), j] * x[i, ncol(x)]/x[nrow(x), ncol(x)]
}
}
chi <- sum( (e-t)^2 / e )
df = (a - 1) * (b - 1)
pv <- pchisq(chi, df = df, lower.tail = FALSE)
s = sprintf("Pearson's Chi-squared test\nChi sq = %.4f , df = %d , P-value = %.5f", chi, df, pv)
cat(s)
}
chisqfun(tbl)
## Pearson's Chi-squared test
## Chi sq = 9.0869 , df = 2 , P-value = 0.01064