Saturday, February 9, 2008

printing a matrix in R

Okay. I know the code to do this exists -- latex in Hmisc. I like the output from this function better though at least for my present purpose.
printMatrix <- function(m, r=2) {
cat("\\left(\\begin{array}{",
rep("c", nrow(m)), "}\n", sep="")
cat(apply(m, 1,
function(row) paste(round(row, r),
collapse=" & ")),
sep=" \\\\\n");
cat("\\end{array}\\right)\n");
}

foo <- function(s3, r=2) {
s <- matrix(c(s3[1], s3[2], s3[2], s3[3]), ncol=2);
cat("$\n")
printMatrix(s, r=r)
cat("$\n\n");
cat("cor: $", cor(s)[1,2], "$\n\n", sep="");
cat("generalized variance: $", det(s), "$\n\n", sep="");
cat("total variance: $", sum(diag(s)), "$\n", sep="");
}

No comments: