### Practicals 6

#1
flowers<-data.frame(K=c(0,0,1,1), Flo=c(0,1,0,1),
                    freq=c(31,33,13,51))
flowers

flo.tab<-xtabs(freq~K+Flo, data=flowers)
#    Flo
# K    0  1
#   0 31 33
#   1 13 51


aa<-chisq.test(flo.tab)
# 	Pearson's Chi-squared test with Yates' continuity
# 	correction
# 
# data:  flo.tab
# X-squared = 10.009, df = 1, p-value = 0.001558

aa$stdres
#    Flo
# K           0         1
#   0  3.349743 -3.349743
#   1 -3.349743  3.349743

library(psych)
phi(flo.tab)
# [1] 0.3

library(ggplot2)
## Illustration of the frequencies by a plot

ggplot(data=flowers, 
  aes(x=as.factor(K), y=freq,fill=as.factor(Flo)))+
  geom_bar(position="dodge", stat="identity")

# stat="identity" is required here because we provide 
# geom_bar with frequencies

# 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.tab<-xtabs(freq~tea+cancer, data=tea.df)
aa<-chisq.test(tea.tab)
# 	Pearson's Chi-squared test
# 
# data:  tea.tab
# X-squared = 16.756, df = 2, p-value = 0.0002299


aa$stdres
#    cancer
# tea          0          1
#   0 -3.6195958  3.6195958
#   B -0.6712472  0.6712472
#   G  3.6223906 -3.6223906

install.packages("epitools")
library(epitools)

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

# Compares both tea types to tea abstinents

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

#Compares the two tea types against each other

#3 
#Carex nigra
cn<-matrix(c(346, 124, 4, 26), nrow=2, byrow=T)
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
phi(cn)
# [1] 0.31


#Cannabis sativa
cs<-matrix(c(340, 150, 10, 0), nrow=2, byrow=T)
chisq.test(cs)
# 	Pearson's Chi-squared test with Yates' continuity
# 	correction
# 
# data:  cs
# X-squared = 3.0369, df = 1, p-value = 0.08139
phi(cs)
# [1] -0.09
#4
cholera<-matrix(c(55, 5, 15, 40), nrow=2, byrow=T)
chisq.test(cholera)
# Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  cholera
# X-squared = 47.289, df = 1, p-value = 6.124e-12
phi(cholera)
# [1] 0.66

### The association is significant but beware 
# that it cannot be interpreted as causal effect (i.e. that
# tetanus vaccine protects against cholera).

