I was discussing some subject with my kids – can’t recall if it was in the realm of astronomy, computing, or moder economics. In any case, it involved large numbers. I fired up R to do a quick calculation:
> 1000000000 / 1000
The resulting answer was less than clear to the grade school mind:
I realize of course that this is a wonderful “teachable moment.” However, I wanted to stay on the subject hand rather than providing an explanation of scientific notation. The format function provided a quick solution.
> format(100000000/1000, scientific=FALSE)
This was better, but how about adding some commas?
> format(100000000/1000, scientific=FALSE, big.mark=”,”)
This is not the only way to do this in R. The prettyNum function provides similar functionality and takes the exact same arguments in this case.
> prettyNum(100000000/1000, scientific=FALSE, big.mark=”,”)
For those from a C background, R provides a wrapper for the sprintf C-library function. You can use positional notation or specify the format parameter. If you do so, the format string is the first parameter. Examples of the use of this function:
> sprintf(20.1, fmt=’%.2f’)
> sprintf(‘%.2f’, 20.1)
A few commonly used format strings that are used regularly are percent (in this case rounded to whole number) and US currency in dollars rounded to pennies.
> sprintf(“%.0f%%”, 66.666)
> sprintf(“$%.2f”, 99.999)