# How to print a LaTeX matrix using xtable in R

I'm trying to get R to print a matrix as a LaTeX matrix using xtable, using the LaTeX environment bmatrix.

a <- matrix(rnorm(25), 5 ,5)
x <- xtable(x)
> print(x, floating=FALSE, tabular.environment="bmatrix", hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)

I get this:

% latex table generated in R 2.14.1 by xtable 1.6-0 package
% Fri May 11 08:16:12 2012
\begin{bmatrix}{rrrrr}
0.70 & 1.30 & -0.44 & 0.97 & -0.86 \\
-1.23 & -0.59 & 0.04 & -0.32 & 0.12 \\
-0.64 & -0.19 & 0.11 & 0.77 & 0.05 \\
0.56 & -0.28 & -2.05 & 1.01 & -1.77 \\
0.02 & -1.24 & 0.51 & -0.49 & 1.23 \\
\end{bmatrix}

Is there a way to suppress the {rrrrr} alignment attribute, or otherwise get xtable to produce a bracketed matrix that I can use in a math environment?

-
Check out the Hmisc package in R and this question: R, Sweave, Hmisc: pretty-print numbers – Alan Munn May 11 '12 at 15:32

Use align argument of xtable, setting alignment string to empty. This produces an empty group after \begin{bmatrix}, which is harmless:

> a <- matrix(rnorm(25), 5 ,5)
> x=xtable(a,align=rep("",ncol(a)+1)) # We repeat empty string 6 times
> print(x, floating=FALSE, tabular.environment="bmatrix",
hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE)
% latex table generated in R 2.14.1 by xtable 1.7-0 package
% Fri May 11 12:44:24 2012
\begin{bmatrix}{}
-0.12 & 0.44 & 0.32 & 1.38 & 0.48 \\
0.68 & 1.08 & 0.03 & 0.73 & -2.08 \\
-0.49 & 0.61 & 1.51 & 2.24 & -2.54 \\
0.31 & 0.72 & 0.06 & -0.47 & 0.02 \\
0.52 & 1.15 & 2.33 & 0.19 & -1.04 \\
\end{bmatrix}
>
-
Excellent, thanks! – Noam Ross May 11 '12 at 17:07