Monday, October 6, 2014

Printing Fewer Digits (or More Digits)

Problem
Your output contains too many digits or too few digits. You want to print fewer or more.

Solution

For print, the digits parameter can control the number of printed digits.
For cat, use the format function (which also has a digits parameter) to alter the formatting of numbers.

Discussion

R normally formats floating-point output to have seven digits:
> pi
[1] 3.141593
> 100*pi
[1] 314.1593
This works well most of the time but can become annoying when you have lots of numbers to print in a small space. It gets downright misleading when there are only a few significant digits in your numbers and R still prints seven.
The print function lets you vary the number of printed digits using the digits parameter:
> print(pi, digits=4)
[1] 3.142
> print(100*pi, digits=4)
[1] 314.2
The cat function does not give you direct control over formatting. Instead, use the format function to format your numbers before calling cat:
> cat(pi, "\n")
3.141593 
> cat(format(pi,digits=4), "\n")
3.142
This is R, so both print and format will format entire vectors at once:
> pnorm(-3:3)
[1] 0.001349898 0.022750132 0.158655254 0.500000000 0.841344746 0.977249868
[7] 0.998650102
> print(pnorm(-3:3), digits=3)
[1] 0.00135 0.02275 0.15866 0.50000 0.84134 0.97725 0.9986
Notice that print formats the vector elements consistently: finding the number of digits necessary to format the smallest number and then formatting all numbers to have the same width (though not necessarily the same number of digits). This is extremely useful for formating an entire table:
> q <- seq(from=0,to=3,by=0.5)
> tbl <- data.frame(Quant=q, Lower=pnorm(-q), Upper=pnorm(q))
> tbl                             # Unformatted print
  Quant       Lower     Upper
1   0.0 0.500000000 0.5000000
2   0.5 0.308537539 0.6914625
3   1.0 0.158655254 0.8413447
4   1.5 0.066807201 0.9331928
5   2.0 0.022750132 0.9772499
6   2.5 0.006209665 0.9937903
7   3.0 0.001349898 0.9986501
> print(tbl,digits=2)             # Formatted print: fewer digits
  Quant  Lower Upper
1   0.0 0.5000  0.50
2   0.5 0.3085  0.69
3   1.0 0.1587  0.84
4   1.5 0.0668  0.93
5   2.0 0.0228  0.98
6   2.5 0.0062  0.99
7   3.0 0.0013  1.00
You can also alter the format of all output by using the options function to change the default fordigits:
> pi
[1] 3.141593
> options(digits=15)
> pi
[1] 3.14159265358979
But this is a poor choice in my experience, since it also alters the output from R’s built-in functions, and that alteration will likely be unpleasant.

See Also

Other functions for formatting numbers include sprintf and formatC; see their help pages for details.

No comments:

Post a Comment