Skip to content
Prev 70662 / 398525 Next

Formatting numbers with a limited amount of digits consistently

Gabor Grothendieck wrote:
formatC with format="f" seems to work for me, though it assumes you're 
specifying decimal places rather than significant digits.  It also wants 
a vector of numbers as input, not a dataframe.  So the following gives 
pretty flexible control over what a table will look like:

 > data.frame(eruptions = formatC(f$eruptions, digits=2, format='f'),
+            waiting = formatC(f$waiting, digits=1, format='f'))
    eruptions waiting
1 1000000.11    79.0
2       1.80    54.0
3       3.33    74.0
4       2.28    62.0
5       4.53    85.0
6       2.88    55.0
I think that formatting tables properly requires some thought, and R is 
no good at thinking.  You can easily recognize a badly formatted table, 
but it's very hard to write down rules that work in general 
circumstances.  It's also a matter of taste, so if I managed to write a 
function that matched my taste, you would find you wanted to make changes.

It's sort of like expecting plot(x, y) to always come up with the best 
possible plot of y versus x.  It's just not a reasonable expectation. 
It's better to provide tools (like abline() for plots or formatC() for 
tables) that allow you to tailor a plot or table to your particular needs.

Duncan Murdoch