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


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


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


dat <-  matrix(c(1000, 100, 10000, 10000,3.145,1700.42), 2)
  booktabs=T,numeric.dollar=F,colheads=c("Col A","Col B","Col C"),colnamesTexCmd="bfseries")


Output .tex file

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


If you manually change this to:


the final .tex file looks like this:


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

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

output of modified tex file