4

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?

1 Answers1

6

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..."
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • Your answer is cleaner than those in the recomendation @akrun used to mark the question as duplicate. – Johan Rosa Aug 20 '19 at 15:04
  • @phiver I understand that aspect, and I am just letting him know what I think, beyond that, posting his answer in the original question is up to him. – Johan Rosa Aug 20 '19 at 15:38