library(readxl)
library(ggplot2)
library(gridExtra)
library(knitr)
library(Rmisc)
library(dplyr)
library(grid)
library(readxl)
library(Rmisc)
library(gmodels)
library(moments)
library(gmodels)
Assignment2_1cTable <- read_excel("C:/Users/Michael Stec/Desktop/MSDS Class stuff/Assignment2_1cTable.xlsx")
View(Assignment2_1cTable)

Test Items starts from here - There are 5 sections - 50 points total

Section 1: (10 points)
(1) R has probability functions available for use (Kabacoff, Section 5.2.3). Using one distribution to approximate another is not uncommon.

(1)(a) (4 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.

  1. The probability of exactly 0 successes.
dpois(0, lambda=5)
## [1] 0.006737947
ppois(0, lambda=5, lower.tail=T)
## [1] 0.006737947
dbinom(0, size=100, prob=0.05)
## [1] 0.005920529
pbinom(0, size=100, prob=0.05, lower.tail=T)
## [1] 0.005920529
  1. The probability of fewer than 6 successes.
sum(dpois(0:5, lambda= 5))
## [1] 0.6159607
ppois(5, lambda=5, lower.tail=T)
## [1] 0.6159607
pbinom(5, size=100, prob=0.05, lower.tail=T)
## [1] 0.6159991
sum(dbinom(0:5, size=100, prob= 0.05))
## [1] 0.6159991

(1)(b) (2 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.

Probabilities_0_10_pois <- c(dpois(x=0:10, lambda=5))
Probabilities_0_10_binom <- c(dbinom(x=0:10, size=100, prob=0.05))
par(mfrow =c(1,2))
barplot.default(Probabilities_0_10_pois, main= "Poisson Probabilites 0-10", col= "blue")
legend ("topright", legend= c("Probabilities"), fill= c("blue"))
dbinom(x=0:10, size=100, prob=0.05)
##  [1] 0.005920529 0.031160680 0.081181772 0.139575678 0.178142642
##  [6] 0.180017827 0.150014856 0.106025537 0.064870888 0.034901296
## [11] 0.016715884
barplot.default(Probabilities_0_10_binom, main= "Binomial Probabilites 0-10", col= "red")
legend ("topright", legend= c("Probabilities"), fill= c("red"))

(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.

  1. (2 points) Calculate the expected value and variance for this distribution using the general formula for mean and variance of a discrete distribution. To do this, you will need to use integer values from 0 to 6 as outcomes along with the corresponding probabilities. Round your answer to 2 decimal places.
x <- c(0,1,2,3,4,5,6)
Probability_of_X <- c(0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001)  
Average <- sum(x*Probability_of_X)
Average_Rounded <- round(Average,2)
Variance <- sum((Probability_of_X*(x-Average)^2))
Variance_Rounded <-  round(Variance,2)
Average_Rounded <- round(Average,2)

Assignment2_1cTable$xtimesP <- Assignment2_1cTable$x*Assignment2_1cTable$`P(x)`
Mean_1c<- c(0+0.23+0.48+0.546+0.520+0.015+0.006)
Assignment2_1cTable$XMinusMeanSquared <- (Assignment2_1cTable$x-Mean_1c)^2
Assignment2_1cTable$XminusMeanSquaredTimesP <- (Assignment2_1cTable$XMinusMeanSquared*Assignment2_1cTable$`P(x)`)
Variance1C <- c(0.69427993+0.14609807+0.00989016+0.26339204+0.63091717+0.03077763+0.01766521)

Assignment2_1cTable
## # A tibble: 7 x 5
##       x `P(x)` xtimesP XMinusMeanSquared XminusMeanSquaredTimesP
##   <dbl>  <dbl>   <dbl>             <dbl>                   <dbl>
## 1     0  0.215   0                3.23                   0.694  
## 2     1  0.23    0.23             0.635                  0.146  
## 3     2  0.24    0.48             0.0412                 0.00989
## 4     3  0.182   0.546            1.45                   0.263  
## 5     4  0.13    0.52             4.85                   0.631  
## 6     5  0.003   0.015           10.3                    0.0308 
## 7     6  0.001   0.006           17.7                    0.0177
StandardDeviation1C <- sqrt(Variance1C)

round(Variance1C,2)
## [1] 1.79
round(StandardDeviation1C,2)
## [1] 1.34
round(Mean_1c,3)
## [1] 1.797
  1. (2 points) Use the cumsum() function and plot the cumulative probabilties versus the corresponding outcomes. Detemine the value of the median for this distribution and show on this plot.
x <- c(0,1,2,3,4,5,6)
Probability_of_X <- c(0.215, 0.230, 0.240, 0.182, 0.130, 0.003, 0.001)  
Average <- sum(x*Probability_of_X)
Average_Rounded <- round(Average,2)
Variance <- sum((Probability_of_X*(x-Average)^2))
Variance_Rounded <-  round(Variance,2)
Average_Rounded <- round(Average,2)

plot(x, cumsum(Probability_of_X), main= "Cumulative Probabilities vs. Corresponding Outcome", 
     xlab= "Correspoinding Outcome", ylab= "Cumulative Probabilities")
points(median(x), median(cumsum(Probability_of_X)), col="Purple")
text(x=2, y=0.3, col="Purple", labels="Median of Distribution is (3,0.867) ")

median(x)
## [1] 3
median(cumsum(Probability_of_X))
## [1] 0.867
Section 2: (10 points)
(2) Conditional probabilities appear in many contexts and, in particular, are used by Bayes’ Theorem. Correlations are another means for evaluating dependency between variables. The dataset “faithful”" is part of the “datasets” package and may be loaded with the statement data(faithful). It contains 272 observations of 2 variables; waiting time between eruptions (in minutes) and the duration of the eruption (in minutes) for the Old Faithful geyser in Yellowstone National Park.

(2)(a) (2 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.

library(datasets)
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
hist(faithful$waiting, main="Waiting Times", xlab= "Waiting Time", ylab="Occurances", col="Blue" )

y1 = c(faithful$eruptions)
y2 = c(faithful$waiting)
  1. (2 points) Identify any observations in “faithful” for which the waiting time exceeds 70 minutes and the eruptions are less than 3.0 minutes. List and show any such observations in a distinct color on a scatterplot of all eruption (vertical axis) and waiting times (horizontal axis). Include a horizontal line at eruption = 3.0, and a vertical line at waiting time = 70. Add a title and appropriate text.
faithful_scatterplot <- ggplot(data = faithful, aes(x= faithful$waiting, y = faithful$eruptions)) +geom_point() + 
  (ggtitle("Eruptions v. Waiting")) + labs (y= "Eruptions", x= "Waiting Time")
faithful_scatterplot + geom_hline(yintercept=3, linetype= "dashed", color="purple", size=1) + 
  geom_vline(xintercept=70, linetype= "dashed", color="purple", size=1)+
  geom_point(color="blue") +
  geom_point(data=faithful, aes(x=71, y=2.383), color="red", size=2)

  Waiting_Time_Exceeds_70mins <- subset(faithful,faithful$waiting > 70 & faithful$eruptions <3.0)
Waiting_Time_Exceeds_70mins
##     eruptions waiting
## 211     2.383      71
  1. (1 point) What does the plot suggest about the relationship between eruption time and waiting time?

This plot suggests that as one waits longer for an eruption the eruption will last longer.


(2)(b) (3 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.

Waiting_Times_Paired <- matrix(faithful$waiting, byrow=T, ncol=2)

plot(Waiting_Times_Paired[,1],Waiting_Times_Paired[,2], main="Checking for Independence of Waiting Times", 
     xlab= "Column 1 of Waiting_Times_Paired", ylab= "Column 2 of Waiting_times_Paired" )

(2)(c) (2) Test the hypothesis of independence with a two-sided test at the 5% level using the Kendall correlation coefficient.

cor.test(Waiting_Times_Paired[,1],Waiting_Times_Paired[,2], method="kendall")
## 
##  Kendall's rank correlation tau
## 
## data:  Waiting_Times_Paired[, 1] and Waiting_Times_Paired[, 2]
## z = -4.9482, p-value = 7.489e-07
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##        tau 
## -0.2935579
Section 3: (10 points)
(3) Performing hypothesis tests using random samples is fundamental to statistical inference. The first part of this problem involves comparing two different diets. Using “ChickWeight” data available in the base R, “datasets” package, execute the following code to prepare a data frame for analysis.
# 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 ...
The data frame, “result”, has chick weights for two diets, identified as diet “1” and “3”. Use the data frame, “result,” to complete the following item.

(3)(a) (2 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”.

Diet1 <- subset(result, subset = (Diet == 1))$weight
Diet3 <- subset(result, subset = (Diet == 3))$weight
par(mfrow = c(1,2))
boxplot(Diet1, main="Weight of Chicks in Diet 1", ylab= "Chick Weight")
boxplot(Diet3, main= "Weight of Chicks in Diet 3", ylab= "Chick Weight")

(3)(b) (2 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(Diet1,Diet3, mu=0, alt= "two.sided", conf=0.95, var=T, paired=F)
## 
##  Two Sample t-test
## 
## data:  Diet1 and Diet3
## t = -3.5955, df = 24, p-value = 0.001454
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -145.67581  -39.42419
## sample estimates:
## mean of x mean of y 
##    177.75    270.30
Working with paired data is another common statistical activity. The “ChickWeight” data will be used to illustrate how the weight gain from day 20 to 21 may be analyzed. Use the following code to prepare pre- and post-data from Diet == “3” for analysis.
# 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) (2 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, main= "Weight Gain in Chicks", xlab="Day 20", ylab= "Day 21")
abline(a=0, b=1, h=NULL, V=NULL, reg=NULL, col= "purple")

(3)(d) (4 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.

library(readxl)

Problem_3D_Chart <- read_excel("C:/Users/Michael Stec/Desktop/R Assignment 2/Problem 3D Chart.xlsx")




alpha3d <- 0.05
length_post <- c(length(post))
length_pre <- c(length(pre))

degrees_Freedom <- c(length(pre)-1)

post_bar <- c(sum(post)/(length(post)))
pre_bar <- c(sum(pre)/(length(pre)))

mean_weight_gained <- c(post_bar-pre_bar)

sd <- sqrt(sum(mean_weight_gained^2)/(degrees_Freedom))
std_error <- sd/sqrt(length_pre)

t_stat_upper <- qt(0.95,degrees_Freedom )

upper_confidence_interval <- mean_weight_gained+ (std_error*t_stat_upper)

critical_value_onesided <- abs(qt(0.05,degrees_Freedom))
critical_value_onesided
## [1] 1.833113
P_Value <- pt(t_stat_upper,degrees_Freedom,lower=F)
P_Value
## [1] 0.05
Problem_3D_Chart
## # A tibble: 9 x 2
##   `Test Type`                   Value
##   <chr>                         <dbl>
## 1 Alpha                          0.05
## 2 Degrees Freedom                9   
## 3 D bar                         11.4 
## 4 Standard Deviation            11.2 
## 5 Standard Error                 3.53
## 6 T-Statistic                    3.23
## 7 Critical Value                 1.83
## 8 One Sided Confidence Interval 17.9 
## 9 P-Value                        0.05
Section 4: (10 points)
(4) Statistical inference depends on using a sampling distribution for a statistic in order to make confidence statements about unknown population parameters. The Central Limit Theorem is used to justify use of the normal distribution as a sampling distribution for statistical inference. Using Nile River flow data from 1871 to 1970, this problem demonstrates sampling distribution convergence to normality. Use the code below to prepare the data. Refer to this example when completing (4)(c) below.
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) (2 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.

library(moments) 

skewness(Nile)
## [1] 0.3223697
kurtosis(Nile)
## [1] 2.695093
par(mfrow=c(1,2))
qqnorm(Nile, col = "red", main= "QQ Plot Nile River Flows")
qqline(Nile, col= "black")
boxplot(Nile, col = "red", main= "Box Plot of Nile River Flows")

(4)(b) (4 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=T))
}

set.seed(127)
sample2 <-rep(1:1000,0)
for(i in 1:1000) {
  sample2[i] <- mean(sample(Nile,64, replace=T))
}

mean_data_frame_Nile1 <- c(mean(sample1))
mean_data_frame_Nile2 <- c(mean(sample2))

sd_data_frame_Nile1 <- c(sd(sample1))
sd_data_frame_Nile2 <- c(sd(sample2))

var_data_frame_Nile1 <- c(var(sample1))
var_data_frame_Nile2 <- c(var(sample2))

dataframeNile1 <- t(data.frame(c(mean_data_frame_Nile1, sd_data_frame_Nile1, var_data_frame_Nile1), 
                               row.names = c("Mean Sample 1", "Standard Deviation Sample 1", "Variance Sample 1"))) 

dataframeNile2 <- t(data.frame(c(mean_data_frame_Nile2, sd_data_frame_Nile2, var_data_frame_Nile2), 
                               row.names = c("Mean Sample 2", "Standard Deviation Sample 2", "Variance Sample 2")))
data_frame_Complete <- data.frame(rbind(dataframeNile1,dataframeNile2), row.names = c("Sample 1", "Sample 2"))

data_frame_Complete
##          Mean.Sample.1 Standard.Deviation.Sample.1 Variance.Sample.1
## Sample 1      918.7349                    41.57159          1728.197
## Sample 2      919.4785                    20.07329           402.937

(4)(c) (4 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.

mean_Nile1 <- mean(sample1)
mean_Nile2 <- mean(sample2)

sd_Nile1 <- sd(sample1)
sd_Nile2 <- sd(sample2)

par(mfrow=c(1,2))
hist(sample1,col="blue",xlab="Flow", ylim = c(0,0.025), xlim = c(750, 1050), freq=F, main="Nile River Flow\n Sample Size 16")
curve(dnorm(x,mean=mean_Nile1,sd=sd_Nile1),col="orange",lwd=2,add=TRUE)

hist(sample2,col="blue",xlab="Flow",  ylim = c(0,0.025), xlim = c(750, 1050), freq=F, main="Nile River Flow\n Sample Size 64")
curve(dnorm(x,mean=mean_Nile2,sd=sd_Nile2),col="orange",lwd=2,add=TRUE)


Section 5: (10 points)
(5) This problem deals with contingency table analysis. This is an example of categorical data analysis (see Kabacoff, pp. 145-151). The “warpbreaks” dataset gives the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. There are 54 observations on 3 variables: breaks (numeric, the number of breaks), wool (factor, type of wool: A or B), and tension (factor, low L, medium M and high H). These data have been studied and used for example elsewhere. For the purposes of this problem, we will focus on the relationship between breaks and tension using contingency table analysis.

(5)(a)(3 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)
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, col= "cyan", main= "Frequency of Breaks", xlab="Breaks")
abline(a=NULL, b=NULL, h= NULL, v=median_breaks, reg=NULL, coef=NULL, col="Purple", untf=FALSE)

number <- ifelse(warpbreaks$breaks<26, "Strictly Below", "Strictly Above")
number <- as.factor(number)

warpbreaks <- cbind(warpbreaks, number)

summary(warpbreaks)
##      breaks      wool   tension            number  
##  Min.   :10.00   A:27   L:18    Strictly Above:29  
##  1st Qu.:18.25   B:27   M:18    Strictly Below:25  
##  Median :26.00          H:18                       
##  Mean   :28.15                                     
##  3rd Qu.:34.00                                     
##  Max.   :70.00
Contingency_Table_warpbreaks <- CrossTable(warpbreaks$tension, warpbreaks$number)
## 
##  
##    Cell Contents
## |-------------------------|
## |                       N |
## | Chi-square contribution |
## |           N / Row Total |
## |           N / Col Total |
## |         N / Table Total |
## |-------------------------|
## 
##  
## Total Observations in Table:  54 
## 
##  
##                    | warpbreaks$number 
## warpbreaks$tension | Strictly Above | Strictly Below |      Row Total | 
## -------------------|----------------|----------------|----------------|
##                  L |             14 |              4 |             18 | 
##                    |          1.943 |          2.253 |                | 
##                    |          0.778 |          0.222 |          0.333 | 
##                    |          0.483 |          0.160 |                | 
##                    |          0.259 |          0.074 |                | 
## -------------------|----------------|----------------|----------------|
##                  M |             10 |              8 |             18 | 
##                    |          0.011 |          0.013 |                | 
##                    |          0.556 |          0.444 |          0.333 | 
##                    |          0.345 |          0.320 |                | 
##                    |          0.185 |          0.148 |                | 
## -------------------|----------------|----------------|----------------|
##                  H |              5 |             13 |             18 | 
##                    |          2.253 |          2.613 |                | 
##                    |          0.278 |          0.722 |          0.333 | 
##                    |          0.172 |          0.520 |                | 
##                    |          0.093 |          0.241 |                | 
## -------------------|----------------|----------------|----------------|
##       Column Total |             29 |             25 |             54 | 
##                    |          0.537 |          0.463 |                | 
## -------------------|----------------|----------------|----------------|
## 
## 
Contingency_Table_warpbreaks
## $t
##    y
## x   Strictly Above Strictly Below
##   L             14              4
##   M             10              8
##   H              5             13
## 
## $prop.row
##    y
## x   Strictly Above Strictly Below
##   L      0.7777778      0.2222222
##   M      0.5555556      0.4444444
##   H      0.2777778      0.7222222
## 
## $prop.col
##    y
## x   Strictly Above Strictly Below
##   L      0.4827586      0.1600000
##   M      0.3448276      0.3200000
##   H      0.1724138      0.5200000
## 
## $prop.tbl
##    y
## x   Strictly Above Strictly Below
##   L     0.25925926     0.07407407
##   M     0.18518519     0.14814815
##   H     0.09259259     0.24074074

(5)(b)(2 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.

CHI <- table(warpbreaks$tension, warpbreaks$number)

chisq.test(CHI, correct=F)
## 
##  Pearson's Chi-squared test
## 
## data:  CHI
## X-squared = 9.0869, df = 2, p-value = 0.01064

(5)(c) (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).

chi <- function(x) {
   # To be used with 2x2 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]
     enew1 <- x[4,1]*x[3,3]/x[4,3]
     enew2 <- x[4,2]*x[3,3]/x[4,3]
   # 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] -enew1)^2/enew1 +
       (x[3,2] - enew2)^2/enew2
     return(list("chi-squared" = chisqStat,
                 "p-value" = pchisq(chisqStat, 1, lower.tail = F)))
}
x <- addmargins (CHI)

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:3) {
       for (j in 1: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
  pv <- pchisq(chi, df = xdf, lower.tail = FALSE) 
 return(cat("Pearson's Chi-squared test \\n","Chi sq: ", chi, "; 
            Degree of Freedom :",xdf," ; P-value :",pv))
}
chisqfun(CHI)
## Pearson's Chi-squared test \n Chi sq:  9.086897 ; 
##             Degree of Freedom : 2  ; P-value : 0.01063667