
###  HERE IS THE IMPORTANT PART: ####
Summing any metric value without first removing the "TOTAL" rows is a mistake

## COMPARE: 

      WITH TOTALS INCLUDED          |     THE CORRECT VALUES
    --------------------------------|-----------------------------
    TTT.calc[, sum(Val), by=Camp]   |     TTT[, sum(Val), by=Camp]   #Original
         Camp  V1                   |          Camp V1
      1:   AA 108                   |       1:   AA 27
      2:   BB 108                   |       2:   BB 27
      3:   CC 128                   |       3:   CC 32


# The solution is to exclude "TOTAL" rows

    TTT.calc[!.("TOTAL", "TOTAL")][, sum(Val), by=Camp]
         Camp V1
      1:   AA 81
      2:   BB 81
      3:   CC 96

PITFALL:  Not knowing all of the columns that have TOTAL rows, or accidentally missing one such column. 




#### CREATING THE SAMPLE DATA: ####
#### ------------------------- ####


  Age <- 1:4 * 10
  Gender <- c("M", "F")
  Camp <- paste0(LETTERS, LETTERS)[1:3]

  TTT <- CJ(Age=Age, Gender=Gender, Camp=Camp)
  TTT[, Val := {set.seed(1); sample(2:5, .N, TRUE)}]

  ## Functino to add total column. Will create a new table which will need to be rbind
  addTotalCol <- function(sumCol) {
    byCol  <- setdiff(keyCols, sumCol)
    cbind( TTT[, list(Val=sum(Val)), by=byCol], 
           rbind(setattr(rep("TOTAL", length(sumCol)), "names", sumCol))
         )
  }

  keyCols <- c("Camp", "Gender", "Age")
  sumCol <- "Gender"

  A  <- addTotalCol(c("Age"))
  G  <- addTotalCol(c("Gender"))
  GA <- addTotalCol(c("Gender", "Age"))

  TTT.calc <- rbindFactorCheck(preserveFactors=TRUE, silent=FALSE,
                l=list(TTT
                  , setcolorder(A,  names(TTT))
                  , setcolorder(G,  names(TTT))
                  , setcolorder(GA, names(TTT))
                ))


  setkey(TTT.calc, "Age", "Gender")
