####################################################
######   Exploratory Techniques R Commands   #######
######       Correspondence Analysis         #######
####################################################

## Correspondence analysis helps identify associations in complex data

## The packages needed for these techniques are: 
ca
FactoMineR
explor

##########################################################
###  Multiple Correspondence Analysis in FactoMineR   ####
##########################################################

# load the packages
library(FactoMineR)
library(explor)

# load the data
df <- read.table(file.choose(), header=T, sep="\t")

# check the data
summary(df, stringsAsFactors = T)

# Perform Multiple Correspondence Analysis
MCAFac = MCA(df, graph= F)
explor(MCAFac)

#################################################
###  Multiple Correspondence Analysis  in ca  ###
#################################################

# The ca library has a range of different algorithms for doing the analysis,
# Good for numerical output

# load the MASS library /  package (this only needs to be done once per session)
library (ca)

# load the data
df <- read.table(file.choose(), header=T, sep="\t")

# check the data
summary(df, stringsAsFactors = T)

# Burt MCA
MCA_Burt <- mjca(df, lambda= "Burt")
plot(MCA_Burt, labels= c(0, 2), col= c("white", "black")) 
summary(MCA_Burt)

# Joint MCA
MCA_Joint <- mjca(df, lambda= "JCA")
plot(MCA_Joint, labels= c(0, 2), col= c("white", "black")) 
summary(MCA_Joint)

# Adjusted MCA
MCA_ADj <- mjca(df, lambda= "adjusted")
plot(MCA_ADj, labels= c(0, 2), col= c("white", "black")) 
summary(MCA_ADj)
##################################################
### Binary Correspondence Analysis  in anacor  ###
##################################################

# This method adds confidence intervals of 0.05 to the plot

# load library / package anacor 
library (anacor)

# load the data
df <- read.table(file.choose(), header=T, sep="\t")

# convert the data to cross-table 
# make sure you have run the script - see file data frame to stab script
xtab = stack.fnc(df)

# check data
xtab

# performs analysis using standard vs. standard scaling. 
# Type "?scaling" for a list of the different scalings.
BCA_Ana <- anacor(xtab, scaling= c("standard", "standard"))
plot(BCA_Ana, plot.type= "jointplot")
summary(BCA_Ana)