## Pracicals 6: Contingency tables
#1
##First, we need to calculate frequencies of plants i each combination of 
# potassium (K) treatment and flowering
# K+ Flo: 51
# K+ NoFlo: 64-51=13
# K- Flo: 33
# K- NoFlo: 64-33=31


fl.mat<-matrix(c(31,13, 33, 51), byrow=T, ncol=2) ## Inputing the data;
# In this case, we create a matrix from a vector, the byrow argument specifies the 
# direction how the matrix is assemmpled
rownames(fl.mat)<-c("NoFlo", "Flo")# adding rownames to matrix
colnames(fl.mat)<-c("K-", "K+")# adding  column names to matrix

fl.mat
#       K- K+
# NoFlo 31 13
# Flo   33 51

##Null hypothesis: Flowering and K application are independent

fl.test<-chisq.test(fl.mat)# Chisq test analysis of the contingency table

fl.test #Displaying the result of the test 

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

## We reject the null on the basis of the test. The two variables are significantly 
# associated

fl.test$stdres ## Display of standardized residuals: shows that there are
# more K+ plants that flowered and K- plants that did not flower than expected under
# null hypothesis 
#              K-        K+
# NoFlo  3.349743 -3.349743
# Flo   -3.349743  3.349743

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

# Phi coefficient also identified a positive association between K application and 
# flowering; this is similar to the standardized residuals, but can be displayed by
# a single number

#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)) #Inputting the data

tea.df

tea.tab<-xtabs(freq~tea+cancer, data=tea.df) # transforming the dataframe
# to a contingency table

# Null hypothesis: there is no association between development of
# cancer and drinking tea

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

library(epitools)#need to be installed first
#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

# Here, important columns are oddsratio and p.value
# oddsratio shows the ratio o chance of deleloping cancer relative to the 
# first level (here 0 - i.e. no tea); p-values show significance of the oodds ratios;
# this is significant for green tea but non-significant for black (p=0.082)


#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

# Here, the greed tea is not identified to be significantly more protective than
# black

## Note, that this is an obvious type of type II error in the system because green is
# significantly better than 0, but not significantly better than black and black
# is not significanntly better than 0.

### Task 3
# First we need to calculate numbers of plots with species and without in 
# wet meadows and outside this habitat, Then we construct a matrix of that

# Carex nigra
Cn<-matrix(c(346 # Cn absent, No WM 
             , 4 # Cn present, No WM
             , 124 # Cn abesnt, WM
             , 26 # Cn present, WM
             ), byrow=T, ncol=2)
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

# There is a significant positive association of Carex nigra with wet meadows

#Festuca rubra
Fr<-matrix(c(224, 30, 126, 120), byrow=T, ncol=2)

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

phi(Fr)
# [1] 0.4


# There is a significant positive association of Festuca rubra with wet meadows

# Cannabis sativa

Cs<-matrix(c(340, 10, 150, 0), byrow=T, ncol=2)
chisq.test(Cs)
# 	Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  Cs
# X-squared = 3.0369, df = 1, p-value = 0.08139


# Cannabis sativa shows no significant association with wet meadows

#just for information, the phi-coefficient (though it is not significantly different from 0)
phi(Cs)
# [1] -0.09

#### Task 4

## At the first glance, this task seems similar to task #1
# So, we could easily compute the analysis like this

# 55 Vaccinated survived
# 5 Vaccinated died
# 15 Nonvaccinated survived
# 40 Nonvaccinated died


cholera<-matrix(c(40, 5, 15, 55), byrow=T, ncol=2)

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

## There is a significant positive association between surviving of cholera and tetanus vacciantion;
# However, that does not mean that tetanus vaccination really protects against cholera beacues this is
# just a coincidence; only relatively rich people with good nutrition get vaccinated
# in a poor country and such people also have a better chance to survive cholera.


### Task 5 

## First we, generate a data frame containing the data
flu<-data.frame(faculty=c("edu", "edu", "sci", "sci", "phil", "phil"),
                flu=rep(c(0,1), 3), freq = c(170-80, 80, 220-190, 190, 290-22, 22))

flu #Checking the content of the df

flu.tab<-xtabs(freq~faculty+flu, data=flu) #Conversion of the dataframe to a contingency table

chisq.test(flu.tab)# Overall goodness of fit test
# 	Pearson's Chi-squared test
# 
# data:  flu.tab
# X-squared = 318.42, df = 2, p-value < 2.2e-16


epitab(flu.tab)# Computation of odds ratios
# $tab
#        flu
# faculty   0         p0   1         p1  oddsratio      lower      upper      p.value
#    edu   90 0.23195876  80 0.27397260 1.00000000         NA         NA           NA
#    phil 268 0.69072165  22 0.07534247 0.09235075 0.05442249  0.1567121 2.911613e-22
#    sci   30 0.07731959 190 0.65068493 7.12500000 4.37001417 11.6168102 5.189936e-17

## Conclusion: based on the test, one would think that there are significant (and pronounced) differences in susceptibility
# of students to flu. However, there is one big problem - students in this test are not independent observations.
# Therefore, the results say absolutely nothing anout their susceptibility to flu. They rather reflect number of contacts 
# during the study and also random effects like the time of the first infection occurrence in the given group. 

