Search code examples
rfunctionautomationformula

R Custom Number Format: Thousands, Millions, Billions


I'm looking for a way to easily format my numbers into strings throughout my document from the basic numbers which look like 21309809 to something more legible like 21.3 million, rounded to correct decimals.

I'm trying to find a way to format thousands with a comma (999,999), millions with one decimal point (9.9 M), and billions with one decimal point (9.9 B).

i.e. In my markdown file there are multiple instances where I need to have this automated in the text, based on certain formulas. Right now, the following: Today, there were `r sum_value` new figures returns as Today, there were 21309809 new figures but I want it to show automatically as Today, there were 21.3 M new figures, and also to adjust automatically as the numbers drop above or below thresholds.


Solution

  • You can create a custom number format function. Here's one that I use at the start of my scripts.

    # Create your function
    custom_number_format <- function(x){ifelse(x > 999999999,
                                           paste(format(round((x/1000000000), 2), 
                                                        nsmall=1, big.mark=","), "B"),
                                           ifelse(x > 999999, 
                                           paste(format(round((x/1000000), 1), 
                                                        nsmall=1, big.mark=","),"M"), 
                                           format(round(x), nsmall=0, big.mark=",")))}
    
    # Now try it out
    custom_number_format(999)
    custom_number_format(999999)
    custom_number_format(1000000)
    custom_number_format(999900000)
    custom_number_format(1000000000)
    

    Then you can throw in that custom_number_format throughout the markdown file and it'll return the right result.