# Load data
tb <- read.table("C:\\a.txt",header=TRUE,sep=",",row.names=1)

# Add a column and a row
tb <- cbind(tb,0)
tb <- rbind(tb,0)

# Store data on the table
nRow <- nrow(tb)
nCol <- ncol(tb)

# Add row totals
rownames(tb)[nRow] <- "Row sum"
i <- 1
while(i <= nRow)
{
    partialRowsum <- sum(tb[i,])
    tb[i,nCol] <- partialRowsum
    i <- i + 1
}


# Add column totals
colnames(tb)[nCol] <- "Columns sum"
i <- 1
while(i <= nCol)
{
    partialColsum <- sum(tb[i])
    tb[nRow,i] <- partialColsum
    i <- i + 1
}


# This function returns a stocastic matrix
# conditioned on the given one.
stoc <- function(mat)
{
    stocIndipTable <- matrix(0,nRow,nCol)
    k<-1
    while(k<=nRow)
    {
        j <- 1
        while(j<=nCol)
        {
            if((j==nCol) || (k==nRow))
            {
                stocIndipTable[k,j] <- tb[k,j]
                j = j + 1
            }else{
                stocIndipTable[k,j] <- tb[k,nCol]*tb[nRow,j]/tb[nRow,nCol]
                j = j + 1
            }
        }
        k = k + 1
    }
    return(stocIndipTable)
}


# Contingency table
ctgTable <- tb-stoc(tb)

# This function calculates the normalized
# Pearson's chi squared (not constrained)
calculatePearson <- function(cgt)
{
    rawP <- cgt^2/stoc(tb)
    pearson <- sum(rawP)
    maxP <- min((nRow-2),(nCol-2)) * tb[nRow,nCol]
    return(pearson/maxP)
}

# Print information on the table
paste("This is a ",dim(tb)[1]," by ",dim(tb)[2]," matrix.")
print(colnames(tb))
print(rownames(tb))

# Pearson's Chi squared
p <- calculatePearson(ctgTable) * 100

if(p>0)
{
    print("There is connection between the two phenomena in the table")
    print(paste("Chi squared connection index: ",p," %"))
}else{
    print("Check process! Chi squared negative!")
}