[R] Bug/Error in formatC? (Was: Why doesn't formatC( x, digits=2, format= "g")...)
Martin Maechler
maechler at stat.math.ethz.ch
Tue Jun 10 15:05:05 CEST 2008
>>>>> "PD" == Peter Dunn <dunn at usq.edu.au>
>>>>> on Tue, 10 Jun 2008 09:25:07 +1000 writes:
PD> Hi all After posting what follows, Duncan Murdoch
PD> suggested perhaps a bug in formatC, or an error on
PD> documentation. Any comments?
It could be called a bug in your platform's
implementation of the C-library internal sprintf()
{to which R's sprintf() is an interface}.
Things work okay for me on three different Linux platforms and
on Solaris SPARC.
More details :
formatC(x, digits=2, format="fg", flag = "#")
ends up calling
sprintf("%#<n>.2g", x)
where the <n> is carefully determined from x,
in your example
sprintf("%#3.2g", 0.005999)
For me, this correctly gives
> sprintf("%#3.2g", 0.005999)
[1] "0.0060"
and I assume that for your platform, it wrongly returns
"0.006" instead.
Can you confirm?
What are the exact platform details?
Martin Maechler, ETH Zurich
PD> In particular, bug, error or not, any ideas about how I
PD> can consistently get two significant figures to print?
PD> P.
PD> ---------- Original Message ----------
PD> Hi all
PD> I am not a C programmer, but I am trying to understand
PD> formatC to get consistent printing of reals to a given
PD> number of significant digits.
PD> Can someone please explain this to me? These first
PD> three give what I expect on reading ?formatC:
>> formatC(0.0059999, digits=2,format="fg",flag="#")
PD> [1] "0.0060"
>> formatC(0.59999, digits=2,format="fg",flag="#")
PD> [1] "0.60"
>> formatC(5.9999, digits=2,format="fg",flag="#")
PD> [1] "6.0"
PD> This seems consistent with what I read (but perhaps do
PD> not understand) in ?formatC, where I read this:
PD> digits the desired number of digits after the
PD> decimal point (format = "f") or significant digits
PD> (format = "g", = "e" or = "fg").
PD> Since I am using format="fg" and digits=2, so I am
PD> expecting two significant digits to always show, which I
PD> have above. So I fail to understand this:
>> formatC(0.000059999, digits=2,format="fg",flag="#")
PD> [1] "0.00006"
>> formatC(0.000059, digits=2, format="fg",flag="#")
PD> [1] "0.000059"
PD> I was expecting both of these to produce "0.000059".
PD> But in the first case above, I get one significant digit
PD> only.
PD> I'm obviously misunderstanding something; can someone
PD> enlighten me? (No doubt, someone will point out a
PD> nuance of the help files I didn't understand!)
PD> Also, since the above obviously doesn't do what I hoped
PD> (consistently printing two sig figs), could someone also
PD> explain how I can consistently get two significant
PD> figures in situation like above?
PD> Thanks as always.
PD> P.
PD> -- Dr Peter Dunn | dunn <at> usq.edu.au Faculty of
PD> Sciences, USQ; http://www.sci.usq.edu.au/staff/dunn
PD> Aust. Centre for Sustainable Catchments:
PD> www.usq.edu.au/acsc
More information about the R-help
mailing list