## Pracicals 6: Contingency tables
#1

fl.mat<-matrix(c(31,13, 33, 51), byrow=T, ncol=2)
fl.test<-chisq.test(fl.mat)

# Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  fl.mat
# X-squared = 10.009, df = 1, p-value = 0.001558

fl.test$stdres

library(psych)
phi(fl.mat)
# [1] 0.3

#2
tea.df<-data.frame(tea=c(0,0,"G", "G", "B", "B"), cancer=c(0,1,0,1,0,1),
                   freq=c(130,55,357,65,160,45))
tea.df

tea.tab<-xtabs(freq~tea+cancer, data=tea.df)

chisq.test(tea.tab)
# Pearson's Chi-squared test
# 
# data:  tea.tab
# X-squared = 16.756, df = 2, p-value = 0.0002299

library(epitools)
#Comparison of black vs. geen tea
#Comparison of both types of tea to no tea
epitab(tea.tab)
# $`tab`
# cancer
# tea   0        p0  1        p1 oddsratio     lower     upper      p.value
# 0 130 0.2009274 55 0.3333333 1.0000000        NA        NA           NA
# B 160 0.2472952 45 0.2727273 0.6647727 0.4209577 1.0498032 8.281283e-02
# G 357 0.5517774 65 0.3939394 0.4303540 0.2852035 0.6493768 9.265908e-05

#Comparison of black vs. geen tea
epitab(tea.tab[2:3,])
# $`tab`
# cancer
# tea   0        p0  1        p1 oddsratio     lower     upper    p.value
# B 160 0.3094778 45 0.4090909 1.0000000        NA        NA         NA
# G 357 0.6905222 65 0.5909091 0.6473701 0.4239252 0.9885895 0.05662229

### Task 3

Cn<-matrix(c(346, 4, 124, 26), byrow=T, ncol=2)
phi(Cn)
# [1] 0.31
chisq.test(Cn)
# Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  Cn
# X-squared = 45.973, df = 1, p-value = 1.199e-11

500-(30+ 126+ 120)
Fr<-matrix(c(224, 30, 126, 120), byrow=T, ncol=2)
phi(Fr)
# [1] 0.4
chisq.test(Fr)
# Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  Fr
# X-squared = 79.582, df = 1, p-value < 2.2e-16

Cs<-matrix(c(490, 10, 150, 0), byrow=T, ncol=2)
phi(Cs)
# [1] -0.07
chisq.test(Cs)
# Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  Cs
# X-squared = 1.8696, df = 1, p-value = 0.1715