Reputation: 939
Is there an easier way to format currencies in R. The following code, generates a small table -
library(dplyr)
set.seed(1)
data = sample(5000:1500000,10, replace = F)
data = tibble(data)
data %>% mutate(currency = scales::dollar(data))
data currency
<int> <chr>
1 457736 $457,736
2 129412 $129,412
3 1490098 $1,490,098
4 861017 $861,017
5 30172 $30,172
6 1348337 $1,348,337
7 1446261 $1,446,261
8 645774 $645,774
9 543190 $543,190
10 1323948 $1,323,948
I will like to generate a new column that formats the data such that -
$457,736 will be $457K
$1,490,098 will be $1.5M
$30,172 will be $30K
Upvotes: 5
Views: 2925
Reputation: 125797
One option would be to make use of scales::label_number_si
like so:
library(dplyr)
set.seed(1)
data = sample(5000:1500000,10, replace = F)
data = tibble(data)
data %>%
mutate(currency = scales::dollar(data),
currency_si = paste0("$", scales::label_number_si(accuracy = .1)(data)),
new_col = paste(currency, "will be", currency_si))
#> # A tibble: 10 x 4
#> data currency currency_si new_col
#> <int> <chr> <chr> <chr>
#> 1 457736 $457,736 $457.7K $457,736 will be $457.7K
#> 2 129412 $129,412 $129.4K $129,412 will be $129.4K
#> 3 1490098 $1,490,098 $1.5M $1,490,098 will be $1.5M
#> 4 861017 $861,017 $861.0K $861,017 will be $861.0K
#> 5 30172 $30,172 $30.2K $30,172 will be $30.2K
#> 6 1348337 $1,348,337 $1.3M $1,348,337 will be $1.3M
#> 7 1446261 $1,446,261 $1.4M $1,446,261 will be $1.4M
#> 8 645774 $645,774 $645.8K $645,774 will be $645.8K
#> 9 543190 $543,190 $543.2K $543,190 will be $543.2K
#> 10 1323948 $1,323,948 $1.3M $1,323,948 will be $1.3M
Upvotes: 3