Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 338
Nibood_the_slightly_advanced Avatar asked Oct 28 '25 04:10

Nibood_the_slightly_advanced


1 Answers

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..."
like image 80
sindri_baldur Avatar answered Oct 29 '25 18:10

sindri_baldur



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!