Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading