[R] NaN/NA and sprintf double format

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Tue May 14 20:56:05 CEST 2002

On Tue, 14 May 2002, Dirk Eddelbuettel wrote:

> With a (late prerelease of) 1.5.0 on Windows, using sprintf on NaN
> yields garbage when the number of decimal is specified while it
> works fine for NA:
> > sprintf("%.2f", NA)
> [1] "0.00"

I get that on Linux too, but why is it fine?  See below.

> > sprintf("%.2f", NaN)
> [1] "-1.#J"
> Not specifying the decimal precision lets both print garbage:
> > sprintf("%f", NaN)
> [1] "-1.#IND00"
> > sprintf("%f", NA)
> [1] "-1.#QNAN0"
> Is this a bug or a feature?

Remember that NA is logical, so this is not correct usage.  Not that the
correct usage works very much better ....

The C code says

/* Simple wrapper for C sprintf function: does very little checking to
   see that the format conversion character and the argument are
   compatible.  This is the user's responsibility!

and I think that should be on the help page.  If it were, this is a

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list