Number Formatting

May 11, 2010
By

(This article was first published on R-Chart, and kindly contributed to R-bloggers)

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:

[1] 1e+06

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)

To leave a comment for the author, please follow the link and comment on his blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.