malana
malana

Reputation: 5220

In R, how to stop xtable from automatically rounding?

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.

Upvotes: 6

Views: 6234

Answers (4)

marcor92
marcor92

Reputation: 537

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"

Upvotes: 2

Daniel Dvorkin
Daniel Dvorkin

Reputation: 16

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.

Upvotes: 0

ROLO
ROLO

Reputation: 4223

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.

Upvotes: 0

James
James

Reputation: 66834

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}

Upvotes: 14

Related Questions