首页 > 解决方案 > 如何在 R 中格式化货币

问题描述

有没有更简单的方法来格式化 R 中的货币。以下代码生成一个小表格 -

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

我想生成一个新列来格式化数据,这样 -

$457,736 will be $457K
$1,490,098 will be $1.5M
$30,172 will be $30K

标签: rdplyr

解决方案


一种选择是scales::label_number_si像这样使用:

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

推荐阅读