[R] How do I format something as "0.000"?

Marc Schwartz MSchwartz at MedAnalytics.com
Mon Jan 17 22:33:50 CET 2005


On Mon, 2005-01-17 at 14:19 -0600, Dirk Eddelbuettel wrote:
> On Mon, Jan 17, 2005 at 04:49:35PM +0100, Christian Hennig wrote:
> > Hi,
> > 
> > I would like to use the format function to get numbers all with three 
> > digits to the right of the decimal point, even in cases where there is no
> > significant digit left. For example, I would like to get
> > c(0.3456789,0.0000053) as "0.346" "0.000".
> > It seems that it is not possible to force format to print a "0.000", i.e.
> > without any significant decimal places.
> > Is it possible to do this somehow in R?
> 
> sprintf can do that
> 
> 	> sprintf("%3.3f %3.3f", 0.3456789, 0.00000053)
> 	[1] "0.346 0.000"
> 
> You'd have to loop over your vector to do it one by one, I think.

To do this in vectorized fashion, you can use formatC():

x <- c(0.3456789, 0.00000053)

> formatC(x, format = "f", digits = 3)
[1] "0.346" "0.000"

See ?formatC for more help.

HTH,

Marc Schwartz




More information about the R-help mailing list