Hi,
For your first condition, this could be used:
gsub("(\\d)[.].*","\\1",498888888.85)
[1] "498888888"
Second condition:
formatC(4333.78889,width=8,format="f",digits=2,flag="0")
#[1] "04333.79"
?formatC(884333.78889,width=8,format="f",digits=2,flag="0")
#[1] "884333.79"
Third condition:
sprintf("%.3f",0.0123556)
#[1] "0.012"
#You can create a function similar to this. (This still have some bugs).
?fun1<-function(x)
?ifelse(x>10^7,gsub("\\d)[.].*","\\1",x),ifelse(x<10^7
&
x>1,formatC(x,width=8,format="f",digits=2,flag="0"),sprintf("%.3f",x))
?)
fun1(488.85)
#[1] "00488.85"
?fun1(0.1233555)
#[1] "0.123"
fun1(VALUES)
# [1] "123456789"? "12345678"?? "1234567.90"
"123456.89"? "12345.79"?
?#[6] "01234.68"?? "00123.57"?? "00012.46"??
"00001.35"?? "0.123"????
#[11] "0.012"????? "0.001"???
A.K.
----- Original Message -----
From: Dennis Fisher <fisher at plessthan.com>
To: r-help at stat.math.ethz.ch
Cc:
Sent: Thursday, August 2, 2012 10:34 PM
Subject: [R] Formatting numbers for display
Colleagues
R 2.15.1
OS X
I have a lengthy script that generates a positive number that I display in a
graphic using text.? The range of possible values is quite large and I am
looking for an efficient means to format.?
??? 1.? If the number is large (e.g., > 10^7), I want to display only the
integer portion.
??? 2.? If it is less than 10^7 but > 1, I want to display 8 characters,
e.g.,
??? ??? 12345.78
??? ??? 1234.678
??? ??? 123.5678
??? 3.? If it is less than 1, I want to display at least three significant
digits, e.g.
??? ??? 0.123
??? ??? 0.0123
??? ??? 0.00123
??? ??? 0.000123
If there are any inconsistencies in my proposal, I apologize.
I can accomplish this by brute force with conditionals, -ceiling(log10(VALUE)),
round.? However, I expect that there is a more efficient approach, possibly
using sprint.
For the "dput"-ers, use the following as potential input:
VALUES??? <- c(123456789, 12345678, 1234567.9, 123456.89, 12345.789,
1234.6789, 123.56789, 12.456789, 1.3456789, 0.123456789, 0.0123456789,
0.00123456789)
Thanks for any thoughts.
Dennis
Dennis Fisher MD
P < (The "P Less Than" Company)
Phone: 1-866-PLessThan (1-866-753-7784)
Fax: 1-866-PLessThan (1-866-753-7784)
www.PLessThan.com
______________________________________________
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.