[Tex/LaTex] R, Sweave, Hmisc: pretty-print numbers

rsweave

I'm creating a LaTeX tables based on a matrix in R using the 'latex' function of the Hmisc package.

dat = matrix(c(1000, 100, 10000, 10000), 2)
latex(dat, file='')

This works (as expected) perfectly.

Additionally I would like to use

prettyNum(dat, '.')

to format the numbers in a more readable way. For example:

 100 -->   100 
1000 --> 1.000

Is there a simple way to combine these functions without breaking the (automatic!) table alignment ('r' for numbers instead of 'l' for character)?

Best Answer

UPDATE

The Hmisc package has been updated, and now allows for arbitrary column specifications. Please see Boris' answer for a simple solution.

Original Answer

One of the problems with the way most R packages generate tables is that they are not easy to adapt to changing functionality within LaTeX. The standard for pretty printing numbers and tables within LaTeX is the siunitx package, which Hmisc doesn't support. There is no simple way around this if you are generating the tables using Sweave unless you post-edit your resultant .tex file.

However, if you are willing to do that, it's not that difficult to generate tables with Hmisc and then replace its r columns with the S column type defined by siunitx.

Here's a example:

.Rnw file

\documentclass{report}
\usepackage[utf8]{inputenc}
\usepackage{siunitx,booktabs}
\sisetup{group-separator={.},group-minimum-digits={3},output-decimal-marker={,}}
\usepackage[noae]{Sweave}
\begin{document}

<<>>=
library("Hmisc")
dat <-  matrix(c(1000, 100, 10000, 10000,3.145,1700.42), 2)
@
<<echo=false,results=tex>>=
latex(dat,table=F,center='centering',file='',
  booktabs=T,numeric.dollar=F,colheads=c("Col A","Col B","Col C"),colnamesTexCmd="bfseries")
@

\end{document}

Output .tex file

When you Sweave this file, you produce the .tex file which contains the following line:

\begin{tabular}{rrr}

If you manually change this to:

\begin{tabular}{SSS}

the final .tex file looks like this:

\documentclass{report}
\usepackage[utf8]{inputenc}
\usepackage{siunitx,booktabs}
\sisetup{group-separator={.},group-minimum-digits={3},output-decimal-marker={,}}
\usepackage[noae]{Sweave}
\begin{document}

\begin{Schunk}
\begin{Sinput}
> library("Hmisc")
> dat <-  matrix(c(1000, 100, 10000, 10000,3.145,1700.42), 2)
\end{Sinput}
\end{Schunk}
% latex.default(dat, table = F, center = "centering", file = "",      booktabs = T, numeric.dollar = F, colheads = c("Col A", "Col B",          "Col C"), colnamesTexCmd = "bfseries") 
%
\centering
\begin{tabular}{SSS}
\toprule
\multicolumn{1}{c}{\bfseries Col A}&\multicolumn{1}{c}{\bfseries Col B}&\multicolumn{1}{c}{\bfseries Col C}\tabularnewline
\midrule
1000&10000&   3.145\tabularnewline
 100&10000&1700.420\tabularnewline
\bottomrule
\end{tabular}
\end{document}

Now siunitx can do its magic, and the output is the following:

output of modified tex file