[R] format numbers without leading or trailing 0s

Bert Gunter gunter.berton at gene.com
Tue Nov 29 18:56:31 CET 2011


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

(somewhat but not completely tested)

> lambda <- c(0, 0.005, 0.01, 0.02, 0.04, 0.08)
> gsub("^0(\\..*[^0])0*$","\\1",lambda)
[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:
> Here's one way to get rid of leading zeros before the
> decimal point:
>
>> gsub("^0\\.", "\\.", as.character(lambda))
> [1] "0"    ".005" ".01"  ".02"  ".04"  ".08"
>
> Sarah
>
> On Tue, Nov 29, 2011 at 12:04 PM, Michael Friendly <friendly at yorku.ca> wrote:
>> 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")
>>
>> --
>
>
> --
> Sarah Goslee
> http://www.functionaldiversity.org
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list