[R] Formatting numbers for display
Tejas Kale
kaletejas2006 at gmail.com
Fri Aug 3 11:44:07 CEST 2012
I think the following code provides output that Dennis wants as well
as gets rid of the white space David mentioned.
digitTruncation <- function(x)
{
ifelse(x>10^7, gsub("(\\d)[.].*", "\\1", x), ifelse(x<1, formatC(x, digits=3,
format='fg'),
formatC(x,
width=length(x),
format='fg',
digits=8,
flag='')))
}
VALUES <- c(123456789, 12345678, 1234567.9, 123456.89, 12345.789,
1234.6789, 123.56789, 12.456789, 1.3456789, 0.123456789, 0.0123456789,
0.00123456789)
digitTruncation(VALUES)
[1] "123456789" "12345678" "1234567.9" "123456.89" "12345.789"
"1234.6789" "123.56789" "12.456789" "1.3456789" "0.123" "0.0123"
"0.00123"
tx <- c( 0.55555555, 55.555555555, 555555555555555.55555555, 55.55)
digitTruncation(tx)
[1] "0.556" "55.555556" "555555555555556" "55.55"
Hope this helps.
Tejas
On Fri, Aug 3, 2012 at 1:41 PM, Berend Hasselman <bhh at xs4all.nl> wrote:
>
>
> David Winsemius wrote
> >
> > I didn't get the same results as requested with a wider variety of
> > tests using those formatting methods. Here's what I could offer:
> >
> > form3 <- function (x) switch(findInterval(x, c( 0, 1, 10^7, Inf)),
> > format(x, digits=3),
> > formatC(x, width=8, format="f",
> > drop0trailing=FALSE),
> > trunc(x) )
> >
> > tx <- c( 0.55555555, 55.555555555, 555555555555555.55555555)
> >
> > > sapply(tx, form3)
> > [1] "0.556" " 55.5556" "555555555555555"
> >
> > (Still not getting the 8 digits in the intermediate value cases. Have
> > not figured out how to get rid of leading space.)
> >
>
> How about this to get rid of leading space:
>
> form3 <- function (x) sub("^ +","", switch(findInterval(x, c( 0, 1, 10^7,
> Inf)),
> format(x, digits=3),
> formatC(x, width=8, format="f",
> drop0trailing=FALSE),
> trunc(x) )
> )
>
> Berend
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Formatting-numbers-for-display-tp4638991p4639018.html
> Sent from the R help mailing list archive at Nabble.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.
More information about the R-help
mailing list