6

How do I disable automatic rounding in this case?

> x <- c(2.222, 3.333, 6.6666)
> df <- data.frame(x)
> df
       x
1 2.2220
2 3.3330
3 6.6666
> xtable(df)

Results in

% latex table generated in R 2.11.1 by xtable 1.5-6 package
% Tue Oct 25 12:13:08 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rr}
  \hline
 & x \\ 
  \hline
  1 & 2.22 \\ 
  2 & 3.33 \\ 
  3 & 6.67 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

I can't find any option in the docs of xtable to turn it off.

malana
  • 5,045
  • 3
  • 28
  • 41

4 Answers4

14

How about digits?

xtable(df,digits=4)
% latex table generated in R 2.12.2 by xtable 1.5-6 package
% Tue Oct 25 11:39:25 2011
\begin{table}[ht]
\begin{center}
\begin{tabular}{rr}
  \hline
 & x \\ 
  \hline
1 & 2.2220 \\ 
  2 & 3.3330 \\ 
  3 & 6.6666 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}
James
  • 65,548
  • 14
  • 155
  • 193
  • 5
    This doesn't exactly answer the question. I have a case where I'd like the numbers displayed as is - I've done all the rounding myself and don't, for example, want integers displaying as 121.0000. – kennyB Nov 10 '15 at 20:48
2

You can do it by transforming all columns into string, although it could generate some warning message:

> xtable(df, display=rep("s",ncol(df)+1))

% latex table generated in R 3.3.3 by xtable 1.8-2 package
% Tue Oct 24 12:43:58 2017
\begin{table}[ht]
\centering
\begin{tabular}{rr}
  \hline
 & x \\ 
  \hline
1 &  2.222 \\ 
  2 &  3.333 \\ 
  3 & 6.6666 \\ 
   \hline
\end{tabular}
\end{table}
Warning message:
In formatC(x = c(2.222, 3.333, 6.6666), format = "s", digits = 2,  :
  trasformo l'argomento in "character" in format="s"
marcor92
  • 417
  • 5
  • 13
0

If you've already formatted the data frame with your preferred rounding and don't want to retype the digits for each column, one solution is to turn everything into text. I just defined a function that I then use elsewhere in place of xtable:

myxtable <- function(x, ...) xtable(apply(x, 2, as.character), ...)

Then the return value of myxtable can be used wherever you'd use the return value of xtable, but with formatting intact.

0

See @James' answer for the correct answer (I didn't even check that as I presumed @mmmasterluke had actually read the docs).

As an alternative you can use toLatex from package memisc:

library(memisc)
x <- c(2.222, 3.333, 6.6666)
df <- data.frame(x)
toLatex(df, digits=4)

gives you

\begin{tabular}{D{.}{.}{4}}
\toprule
\multicolumn{1}{c}{x} \\
\midrule
2.2220 \\
3.3330 \\
6.6666 \\
\bottomrule
\end{tabular}

And it has loads of other options which you can use to configure your Latex output.

ROLO
  • 4,183
  • 25
  • 41