3

I just want to set an option in R that will show all numbers with the thousand localized separator.

I saw many posts that cover the format and formatC, but I need to call the function each time.

formatC(1:10 * 100000, format="d", big.mark=",")

There has to be a solution just like for the digits, such as

options(digits = 5)

Thanks.

Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
stuski
  • 199
  • 1
  • 11

2 Answers2

4

A simple workaround could be to define a dedicated function to print numbers with a thousand separator, which could be called, e.g., printT():

printT <- function(x) {formatC(x, format="d", big.mark=",")}

Example:

printT(1:10 * 100000)
[1] "100,000"   "200,000"   "300,000"   "400,000"   "500,000"   "600,000"   "700,000"  
[8] "800,000"   "900,000"   "1,000,000"
RHertel
  • 23,412
  • 5
  • 38
  • 64
3

As mentioned in my comment, the easiest way I can think of would be to add a thousands option to the argument list of print.default and an if() statement in the body.

print.default <- function (x, digits = NULL, quote = TRUE, na.print = NULL, print.gap = NULL, 
                           right = FALSE, max = NULL, useSource = TRUE, thousands = TRUE, ...) 
{
    noOpt <- missing(digits) && missing(quote) && missing(na.print) && 
        missing(print.gap) && missing(right) && missing(max) && 
        missing(useSource) && missing(...)
    if(thousands) {
        return(formatC(x, format="d", big.mark=","))
    }
    .Internal(print.default(x, digits, quote, na.print, print.gap, 
                            right, max, useSource, noOpt))
}

Now we will have to wrap with print, but it works well.

print(1:10 * 100000)
# [1] "100,000"   "200,000"   "300,000"   "400,000"   "500,000"   "600,000"  
# [7] "700,000"   "800,000"   "900,000"   "1,000,000"
print(1:10 * 100000, thousands=FALSE)
# [1] 1e+05 2e+05 3e+05 4e+05 5e+05 6e+05 7e+05 8e+05 9e+05 1e+06
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • That's really nice. Do you think that it would it be possible to easily set and remove the "thousands" option separately instead of passing it as an argument to `print()`? The default value is surely helpful, but I think that it could lead to an unintended use of this option in other cases. – RHertel Mar 03 '18 at 22:30
  • 1
    @RHertel - according to [this answer from Roland](https://stackoverflow.com/questions/34638307/changing-how-output-is-printed-to-the-console/34638830#34638830), we would have to re-write code at the C level to change default printing for numerics (and characters). – Rich Scriven Mar 03 '18 at 22:33
  • 1
    I see. Thanks. This probably does not qualify as "easily possible" :-) – RHertel Mar 03 '18 at 22:34
  • thank you Rich! At least it confirms that it wasn't a straight forward solution. – stuski Mar 03 '18 at 22:55