Search code examples
rnumber-formatting

Format a number 1000 as 1k, 1000000 as 1m etc. in R


I need to display numbers using abbreviations like so

1 shows as 1
999 shows as 999
1000 shows as 1K
999000 shows as 999K
1000000 shows as 1M
1500000 shows as 1.5M
1000000000 shows as 1G
etc...

I have seen the question asked all over stackoverflow for other languages (at least thrice for Javascript):

Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc

Format a number as 2.5K if a thousand or more, otherwise 900

How to format numbers similar to Stack Overflow reputation format

1000000 to 1M and 1000 to 1K in oracle query

1000 to 1k, 1000000 to 1m etc. number abbreviation

...but I was unable to find anything for R. Am I missing something?


Solution

  • Using dplyr::case_when:

    so_formatter <- function(x) {
      dplyr::case_when(
          x < 1e3 ~ as.character(x),
          x < 1e6 ~ paste0(as.character(x/1e3), "K"),
          x < 1e9 ~ paste0(as.character(x/1e6), "M"),
          TRUE ~ "To be implemented..."
      )
    }
    
    test <- c(1, 999, 1000, 999000, 1000000, 1500000, 1000000000, 100000000000)
    so_formatter(test)
    
    
    # [1] "1"                   
    # [2] "999"                 
    # [3] "1K"                  
    # [4] "999K"                
    # [5] "1M"                  
    # [6] "1.5M"                
    # [7] "To be implemented..."
    # [8] "To be implemented..."