(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() or ppois() with probability p = 0.05, and n = 100. Then, estimate the same probabilities using dbinom() or pbinom(). Show the numerical results of your calculations.
dpois(0,lambda = 5)
## [1] 0.006737947
dbinom(0,100,.05)
## [1] 0.005920529
lower.tail logical; if TRUE (default), probabilities are P[X ??? x], otherwise, P[X > x].
pbinom(5,100,.05)
## [1] 0.6159991
The binomial may also be approximated via the normal distribution. Estimate the following binomial probabilities using dnorm() or pnorm(), this time with probability p = 0.25 and n = 100. Then, calculate the same probabilities using dbinom() and pbinom(). Use continuity correction. Show the numerical results of your calculations.
mu<-100*(.25)
sdev<-sqrt((100*.25*(1-.25)))
pnorm(25.5,mu,sdev)-pnorm(24.5,mu,sdev)
## [1] 0.09192744
dbinom(25,100,.25)
## [1] 0.09179969
lower.tail logical; if TRUE (default), probabilities are P[X ??? x], otherwise, P[X > x].
pnorm(19,mu,sdev)
## [1] 0.08292833
(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.
pois<-dpois(0:10,lambda = 5)
binom<-dbinom(0:10,100,.05)
par(mfrow = c(1,2))
barplot(pois,names.arg=c(0:10),main ="Poisson Probability",col="blue",xlab = "Outcome",ylab ="Probability")
barplot(binom,names.arg=c(0:10),main = "Binomial Probability",col = "green",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:6)
prob<-c(0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001)
#expected value
expx<-round(sum(x*prob),digits = 2)
expx
## [1] 1.8
#variance
varx<-round(sum((x-expx)^2*prob),digits = 2)
varx
## [1] 1.79
cumprob<-cumsum(prob)
ggplot(data=NULL,aes(x,cumprob))+geom_point(size=3)+ggtitle("Cum Probabilities vs Outcomes")+xlab("outcomes")+ylab("Cumulative Probabilites")+
theme(plot.title = element_text(hjust = 0.5))+annotate(geom="text",x=1.8,y=.5,label="median at outcome 2 ")+geom_step()
(2)(a) (3 points) Load the “faithful” dataset and present summary statistics and a histogram of waiting times. Additionally, compute the empirical conditional probability of an eruption less than 3.0 minutes, if the waiting time exceeds 70 minutes.
data(faithful, package = "datasets")
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
ggplot(faithful,aes(waiting))+geom_histogram(bins=14,color="black",fill="lightblue")
wait_70 <- faithful %>% filter(waiting>70)
erupt_3<- wait_70 %>% filter(eruptions<3)
nrow(erupt_3)/nrow(wait_70)
## [1] 0.006060606
ggplot(faithful,aes(waiting,eruptions,col=waiting>70 & eruptions<3))+geom_point()+geom_vline(xintercept=70,col="blue")+geom_abline(intercept = 3,slope = 0,col="blue")+ggtitle("eruptions vs waiting times")+theme(plot.title = element_text(hjust = 0.5))
*** There is generally a posititve correlation between waiting times an eruptions times.***
(2)(b) (4 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.
pairs<-data.frame(matrix(faithful$waiting,ncol=2,byrow = TRUE))
ggplot(pairs,aes(X1,X2))+geom_point(col="red")+xlab("Column 1")+ylab("Column2")
(2)(c) (3) Test the hypothesis of independence with a two-sided test at the 5% level using the Kendall correlation coefficient. The cor.test() function can be used to structure this test and specify the appropriate - Kendall’s tau - method.
cor.test(pairs[,1],pairs[,2],method="kendall",alternative = "two.sided",conf.level = .95)
##
## Kendall's rank correlation tau
##
## data: pairs[, 1] and pairs[, 2]
## z = -4.9482, p-value = 7.489e-07
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
## tau
## -0.2935579
# load "ChickWeight" dataset
data(ChickWeight, package = "datasets")
# There are multiple ways to approach the subsetting task. The method you choose is up
# to you.
chick_subset<- ChickWeight %>% filter(Time==21) %>% filter(Diet==1|Diet==3)
head(chick_subset)
## weight Time Chick Diet
## 1 205 21 1 1
## 2 215 21 2 1
## 3 202 21 3 1
## 4 157 21 4 1
## 5 223 21 5 1
## 6 157 21 6 1
# The values in your subsetted data frame should match those below:
# > head(df)
# weight Time Chick Diet
# 12 205 21 1 1
# 24 215 21 2 1
# 36 202 21 3 1
# 48 157 21 4 1
# 60 223 21 5 1
# 72 157 21 6 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”.
diet_1<-ggplot(subset(chick_subset,Diet==1),aes(Diet,weight))+geom_boxplot(col="blue")+ggtitle("Diet1")+theme(plot.title = element_text(hjust = 0.5))
diet_3<-ggplot(subset(chick_subset,Diet==3),aes(Diet,weight))+geom_boxplot(col="red")+ggtitle("Diet3")+theme(plot.title = element_text(hjust = 0.5))
grid.arrange(diet_1,diet_3,nrow=1)
(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(subset(chick_subset,Diet==1)$weight,subset(chick_subset,Diet==3)$weight,alternative = "two.sided",conf.level = .95)
##
## Welch Two Sample t-test
##
## data: subset(chick_subset, Diet == 1)$weight and subset(chick_subset, Diet == 3)$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
# There are multiple ways to approach the subsetting task. The method you choose is up
# to you.
time_20<- ChickWeight%>% filter(Time==20)%>% filter(Diet==3) %>% select(weight)
time_21<- ChickWeight%>% filter(Time==21)%>% filter(Diet==3) %>% select(weight)
time_20
## weight
## 1 235
## 2 291
## 3 156
## 4 327
## 5 361
## 6 225
## 7 169
## 8 280
## 9 250
## 10 295
time_21
## weight
## 1 256
## 2 305
## 3 147
## 4 341
## 5 373
## 6 220
## 7 178
## 8 290
## 9 272
## 10 321
# The first six (6) elements of your Time == 20 vector should match those below:
# [1] 235 291 156 327 361 225
(3)(c) (3 points) Present a scatterplot of the Time == 21 weights as a function of the Time == 20 weights. Include a diagonal line with zero intercept and slope equal to one. Title and label the variables in this scatterplot.
times<-cbind(time_20,time_21)
names(times)[1]<-"time 20 weights"
names(times)[2]<-"time 21 weights"
ggplot(times,aes(`time 20 weights`,`time 21 weights`))+geom_point(cex=2,col='red')+ggtitle("time20 vs time 21 weights")+theme(plot.title = element_text(hjust = 0.5))+geom_abline(intercept = 0,slope = 1)
(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.
mean_20<- mean(time_20$weight)
mean_21<-mean(time_21$weight)
std.dev_20<-sd(time_20$weight)
std.dev_21<-sd(time_21$weighht)
diff<-time_21$weight-time_20$weight
diff_mean<-mean(diff)
n<-length(diff)
#check
t.test(time_21$weight,time_20$weight,paired = TRUE,conf.level = .95,alternative = "greater")
##
## Paired t-test
##
## data: time_21$weight and time_20$weight
## t = 3.2253, df = 9, p-value = 0.005201
## alternative hypothesis: true difference in means is greater than 0
## 95 percent confidence interval:
## 4.920696 Inf
## sample estimates:
## mean of the differences
## 11.4
se<-sd(diff)/sqrt(n)
se
## [1] 3.534591
t_stat<-diff_mean/se
t_stat
## [1] 3.225267
df<-n-1
df
## [1] 9
pvalue<-pt(q=t_stat,df=df,lower.tail = FALSE)
pvalue
## [1] 0.00520061
crit_t<-qt(p=(1-.05),df=df)
conf_int<-c(diff_mean-(crit_t*se),"INFINITY")
conf_int
## [1] "4.92069557913543" "INFINITY"
data(Nile, package = "datasets")
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. 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))
skewness(Nile)
## [1] 0.3223697
kurtosis(Nile)
## [1] 2.695093
boxplot(Nile,main="Nile flow boxplot",col="blue")
qqnorm(Nile,main="Nile flow QQ Plot",col="blue")
qqline(Nile,main="Nile flow QQ Plot",col="blue")
(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.
set.seed(124)
sample1<-rep(1:1000,0)
for(i in 1:1000) {
sample1[i]<-mean(sample(Nile,16,replace=TRUE))
}
set.seed(127)
sample2<-rep(1:1000,0)
for(i in 1:1000) {
sample2[i]<-mean(sample(Nile,64,replace = TRUE))
}
row_names<-c("sample1","sample2")
col_names<-c("mean","sample std dev","sample variance")
matrix(c(mean(sample1),mean(sample2),sd(sample1),sd(sample2),var(sample1),var(sample2)),nrow = 2,ncol = 3,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.
# Create histograms of "sample1" and "sample2" with normal density curves superimposed
par(mfrow = c(1, 2))
hist(sample1,xlim = c(750, 1050),ylim = c(0, 0.025),freq = FALSE)
curve(dnorm(x, mean=mean(sample1), sd=sd(sample1)),
col="darkblue", lwd=2, add=TRUE, yaxt="n")
hist(sample2,xlim = c(750, 1050),ylim = c(0, 0.025),freq = FALSE)
curve(dnorm(x, mean=mean(sample2), sd=sd(sample2)),
col="darkblue", lwd=2, add=TRUE, yaxt="n")
par(mfrow=c(1,1))
(5)(a)(4 points) warpbreaks is part of the “datasets” package and may be loaded via data(warpbreaks). Load “warpbreaks” and present the structure using str(). 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.
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. Present a summary of the augmented dataset using summary(). Present a contingency table of the frequency of breaks using the two variables “tension” and “number”. There should be six cells in this table.
data(warpbreaks, package = "datasets")
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 ...
median_breaks<-median(warpbreaks$breaks)
hist(warpbreaks$breaks)
abline(v=median_breaks,col="blue")
number<-ifelse(warpbreaks$breaks>median_breaks,"above","below")
warpbreaks_2<-warpbreaks %>% mutate(number)
summary(warpbreaks_2)
## breaks wool tension number
## Min. :10.00 A:27 L:18 Length:54
## 1st Qu.:18.25 B:27 M:18 Class :character
## Median :26.00 H:18 Mode :character
## Mean :28.15
## 3rd Qu.:34.00
## Max. :70.00
contingency<-table(warpbreaks_2$tension,warpbreaks_2$number)
contingency
##
## above below
## L 12 6
## M 9 9
## H 4 14
(5)(b)(3 points) Using the table constructed in (5)(a), test at the 5% level the null hypothesis of independence using chisq.test() (Black, Business Statistics, Section 16.2). Show the results of this test and state your conclusions.
chisq.test(contingency)
##
## Pearson's Chi-squared test
##
## data: contingency
## X-squared = 7.2993, df = 2, p-value = 0.026
#p value is below .05 so we reject the null hypothesis and the variables are not idenpendent
(5)(c) (4 points) ‘Manually’ calculate the chi-squared statistic and p-value of the table from (5)(a). The addmargins() function can be used to add row and column sums to the table; useful for calculating the expected values for each cell. You should be able to match the chi-squared and p-values from (5)(b). The underlying code for the chisq.test() function can be viewed by entering chisq.test - without parentheses - in the Console. You are given code below to create the table, add row and column sums and calculate the expected values for the for the first two (2) of three (3) rows. You will need to add code to calculate the expected values for the third row and the chi-squared. The pchisq() function can be used to return the p-value.
x<-addmargins(contingency)
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]
chi_sq <- (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
chi_sq
## [1] 7.29931
pchisq(chi_sq,2,lower.tail = FALSE)
## [1] 0.02600009
(5)(d) (4 points) Build a user-defined function, using your code for (5)(c).We want to pass our (5)(a) table to our function and have it return the chi-squared statistic and p-value. You’re provided with the ‘shell’ of a function and will need to add code to calculate the expected values, the chi-squared statistic, the p-value and return (i.e. output) the chi-squared and p-value. You should call your function and confirm that the output includes the expected chi-squared and p-value.
chisq_function <- function(x) {
# Code for calculating the expected values
x<-addmargins(contingency)
# Code for calculating the chi-squared
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]
chi_sq <- (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
# Code for calculating the degrees of freedom and p-value
chi<-chi_sq
df<-nrow(x)-1
p<-pchisq(chi_sq,2,lower.tail = FALSE)
# Code to ouput the chi-squared, degrees of freedom and p-value
return(c("Chi Squared test",chi,"degrees of freedom",df,"p-value",p))
}
chisq_function(x)
## [1] "Chi Squared test" "7.29931034482759" "degrees of freedom"
## [4] "3" "p-value" "0.026000092782384"
You do not need to do anything with the below. It is provided only for demonstration purposes. In (5)(d), we know the size of the table - 3 x 2 - and write a function to match. Often, though, we’ll want to write functions that are flexible in some way.
# Below is a function that should return the same values as chisq.test() and your
# function from (5)(d). Here, though, the function loops over the rows and columns
# to calculate the expected values. Ideally, this function would work for any sized
# table.
chisqfun <- function(t) {
x <- addmargins(t)
e <- matrix(0, nrow = nrow(t), ncol = ncol(t), byrow = T)
r <- matrix(0, nrow = nrow(t), ncol = ncol(t), byrow = T)
for (i in 1:dim(t)[1]) {
for (j in 1:dim(t)[2]) {
e[i,j] = x[nrow(x),j] * x[i,ncol(x)]/x[nrow(x), ncol(x)]
r[i,j] = ((x[i,j] - e[i,j])^2)/e[i,j]
}
}
chi <- sum(r)
xdf <- (nrow(t) - 1) * (ncol(t) - 1)
pv <- pchisq(chi, df = xdf, lower.tail = FALSE)
return(list("chi-squared" = chi, "degrees_of_freedom" = xdf, "p-value" = pv))
}