[R] "digits" doesn't work in format function
    Marc Schwartz 
    marc_schwartz at comcast.net
       
    Thu Mar 22 16:12:32 CET 2007
    
    
  
On Thu, 2007-03-22 at 09:59 -0500, Baoqiang Cao wrote:
> Dear All,
> 
> I was trying to format a numeric vector (100*1) by using
> outd <- format(x=m, sci=F, digits=2)
> 
> > outd[1:10]
>  [1] " 0.01787758" "-0.14760306" "-0.45806041" "-0.67858525" "-0.64591748"
>  [6] "-0.05918100" "-0.25632276" "-0.15980138" "-0.08359873" "-0.37866688"
> >m[1:10]
>  [1]  0.017878 -0.147603 -0.458060 -0.678585 -0.645917 -0.059181 -0.256323
>  [8] -0.159801 -0.083599 -0.378667
> 
> I'm expecting something like, 0.02 -0.15 ...
> 
> Any advice how to fix it will be highly appreciated!
> 
> Best,
>  Baoqiang
The digits argument pertains to the number of _significant digits_. 
>From ?format:
how many significant digits are to be used for numeric and complex x.
The default, NULL, uses getOption(digits). This is a suggestion: enough
decimal places will be used so that the smallest (in magnitude) number
has this many significant digits, and also to satisfy nsmall. (For the
interpretation for complex numbers see signif.)
If you want tight and consistent control over the number of digits after
the decimal place, you would need to use ?sprintf or ?formatC:
> sprintf("%.2f", m)
 [1] "0.02"  "-0.15" "-0.46" "-0.68" "-0.65" "-0.06" "-0.26" "-0.16"
 [9] "-0.08" "-0.38"
> formatC(m, format = "f", digits = 2)
 [1] "0.02"  "-0.15" "-0.46" "-0.68" "-0.65" "-0.06" "-0.26" "-0.16"
 [9] "-0.08" "-0.38"
HTH,
Marc Schwartz
    
    
More information about the R-help
mailing list