1

Possible Duplicate:
Controlling digits in R

Is there way to show up to the 3rd decimal place of every number in a matrix in R for numbers like 0.12 or 0? I want to force R to show 0.120 and 0.000 instead of 0.12 or 0.

I want to do this because my ultimate goal is to export an R matrix to latex as a table.

Community
  • 1
  • 1
FairyOnIce
  • 2,526
  • 7
  • 27
  • 48
  • 4
    `?sprintf, e.g. sprintf("%1.3f",0.12)` ? – Ben Bolker Oct 26 '12 at 03:06
  • 9
    You asked six questions and have not accepted a single one. At some point people will stop bothering to reply. – Dirk Eddelbuettel Oct 26 '12 at 03:23
  • 1
    What @DirkEddelbuettel said. In addition to thanking people in comments you should accept the best answer and upvote all useful answers. It's the least you can do to show appreciation for the time and effort people put into writing articulate solutions. – Maiasaura Oct 26 '12 at 04:10
  • 2
    Sorry, I did not know how to "accept" the answers. Thank you for telling me that. – FairyOnIce Oct 26 '12 at 04:52
  • `ifelse(0==round(p.value,3),"0.000",round(p.value, 3))`this may also work. – x2yline Mar 03 '18 at 15:54

1 Answers1

5

I think the digits argument of the xtable package does what you want:

> library(xtable)
> xtable(data.frame(a=0.12,b=0),digits=3)
% latex table generated in R 2.16.0 by xtable 1.7-0 package
% Thu Oct 25 23:06:50 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrr}
  \hline
 & a & b \\ 
  \hline
1 & 0.120 & 0.000 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • sprintf is exactly the function that I have been looking for FOR YEARS!! Thank you so much. I wish I knew this earlier!! – FairyOnIce Oct 26 '12 at 03:13
  • 2
    that's fine, but do note that `xtable` is probably cleaner and easier if you want to export to LaTeX ... also, note that if your questions are satisfactorily answered on StackOverflow, you should accept an answer by clicking on the check mark next to it ... – Ben Bolker Oct 26 '12 at 03:14