Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R thousand separator format

Tags:

r

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.

like image 375
stuski Avatar asked May 24 '26 09:05

stuski


2 Answers

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"
like image 163
RHertel Avatar answered May 27 '26 03:05

RHertel


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
like image 39
Rich Scriven Avatar answered May 27 '26 03:05

Rich Scriven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!