tags:

views:

51

answers:

2

Is there a way to change the default number formatting in R so that numbers will print a certain way without repeatedly having to use the format() function? For example, I would like to have

> x <- 100000
> x
[1] 100,000

instead of

> x <- 100000
> x
[1] 100000
+1  A: 

I don't know how to change the default (in fact, I would advise against it because including the comma makes it a character).

You can do this:

> prettyNum(100000, big.mark=",", scientific=FALSE)
[1] "100,000"
Shane
A: 

Well if you want to save keystrokes, binding the relevant R function to some pre-defined key-strokes, is fast and simple in any of the popular text editors.

Aside from that, I suppose you can always just write a small formatting function to wrap your expression in; so for instance:

fnx = function(x){print(formatC(x, format="d", big.mark=","), quote=F)}

> 567 * 43245
[1] 24519915

> fnx(567*4325)
[1] 2,452,275

R has several utility functions that will do this. I prefer "formatC" because it's a little more flexible than 'format' and 'prettyNum'.

In my function above, i wrapped the formatC call in a call to 'print' in order to remove the quotes (") from the output, which i don't like (i prefer to look at 100,000 rather than "100,000").

doug
Thanks Doug. One question: when I try to pass in a large number, I get an NA back. For example, fnx(2200000000) yields NA on my machine, but fnx(2100000000) and lower works fine.
Abiel
Thanks, i wasn't aware of that. Here's the fix: print(formatC(a, big.mark=",", digits=0, format="f", width=12), quote=F). All i've done is replace "d" (for integer) with "f" (for float) and add 'digits=0', so no decimals are printed. By changing to float,the memory allocated to the object is automatically increased (versus integer).
doug