##
#
# MEBn5033 In-class practice without solutions 08: contingency tables and chi-square test
#
##

#
# 1. install and load library MASS and inspect the "survey" data frame
#

library(MASS)

survey
head(survey)

attach(survey)

#
# 2. create a contingency table out of variables Smoke and Sex
#


# first, install and load library gmodels

library(gmodels)

# second, specify the variables W.Hnd and Sex within the CrossTable function; inspect the output

?CrossTable


#
# 3. use function table to produce joint frequencies of the W.Hnd and Sex variables
# save the output to a new object
#

?table


# use margin.table function to see marginal frequencies
?margin.table


#
# 4. calculate the chi-square test (table function output) on this data and interpret the results
#

?chisq.test


# 5. use chisq.test function with "correct" argument set to F (does not apply Yates' correction)



# 6. save the chisq.test output and inspect the object (hint: use $ operator)



c$statistic   # chi-square test statistic
c$p.value     # p-value
c$parameter   # degrees of freedom
c$method      # method
c$data.name   # name of data set
c$observed    # observed values
c$expected    # expected values
c$residuals   # residuals (observed - expected values)
c$stdres      # std. deviations of residuals (difference of observed - expected values in std. deviations)


#
# 7. calculate the chi-square statistic "by hand" on the below defined matrix
#

m <- matrix(c(5, 10, 10, 5), nrow = 2, ncol = 2, byrow = T)
m

# 8. calculate expected values

# expected value


# expected value matrix


# 9. calculate squared differences between observed and expected values 


# 10. divide the results by expected values and sum up the results


