Skip to content

format numbers without leading or trailing 0s

5 messages · Michael Friendly, Sarah Goslee, Bert Gunter +2 more

#
A simple question, but I can't find something to do what I want:

Given: a vector of numbers, like

lambda <- c(0, 0.005, 0.01, 0.02, 0.04, 0.08)

Desired: format them in minimal space for use as plot labels, ie, 
without leading or tailing 0s. For this example:

lambdaf <- c("0", .005", ".01", ".02", ".04", ".08")
#
Here's one way to get rid of leading zeros before the
decimal point:
[1] "0"    ".005" ".01"  ".02"  ".04"  ".08"

Sarah
On Tue, Nov 29, 2011 at 12:04 PM, Michael Friendly <friendly at yorku.ca> wrote:

  
    
#
.. and if you want to simultaneously handle possible multiple trailing
zeros (not sure whether this could even happen)

(somewhat but not completely tested)
[1] "0"    ".005" ".01"  ".02"  ".04"  ".08"

Note that the as.character() coercion is done automatically (and is
documented to be).

If you do much of this, it's worth going through one of the many web
tutorials on regular expressions. And if you're a minimalist like me,
you may even find R's man page, ?regexp), suffices.

Cheers,
Bert
On Tue, Nov 29, 2011 at 9:09 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:

  
    
#
You may also want to deal with a possible
leading negative sign:

  > lambda <- c(0, 0.005, 0.01, 0.02, 0.04, 0.08,
               -0.005, -0.01, -0.02, -0.04, -0.08, 1000)
  > gsub("^0(\\..*[^0])0*$","\\1", lambda)
   [1] "0"      ".005"   ".01"    ".02"    ".04"    ".08"   
   [7] "-0.005" "-0.01"  "-0.02"  "-0.04"  "-0.08"  "1000"  
  > gsub("^(-)?0(\\..*[^0])0*$","\\1\\2", lambda) # -0. -> .
   [1] "0"     ".005"  ".01"   ".02"   ".04"   ".08"   "-.005"
   [8] "-.01"  "-.02"  "-.04"  "-.08"  "1000"

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
Omitting the leading zero is dangerous, since the decimal point can disappear in a poor hardcopy leading to later misinterpretation.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
Michael Friendly <friendly at yorku.ca> wrote: