#' a simple function to add totals to a contingency table (or matrix)
#' of any size. Especially useful for contingency table investigation.
#'
#' @param mat the name of the matrix, either labelled or not.
#'
#' @return a matrix with an additional row and column giving totals.
#' @examples
#' X = matrix(1:12,3)
#' tots(X)
tots=function(mat){
NC = ncol(mat); NR = nrow(mat)
MAT=matrix(,NR+1,NC+1)
MAT[1:NR,1:NC]=mat
if(sum(nchar(dimnames(mat)))==0){
colnames(mat)=rep("",NC)
rownames(mat)=rep("",NR)
}
dimnames(MAT)=list(c(dimnames(mat)[[1]],"total"),
c(dimnames(mat)[[2]],"total"))
names(dimnames(MAT))=names(dimnames(mat))
MAT[1:NR,NC+1]=rowSums(mat)
MAT[NR+1,1:(NC+1)]=colSums(MAT[-(NR+1),])
return(MAT)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.