r - 如何在 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
解决方案
一种选择是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
推荐阅读
- javascript - 最省时的路线
- kubernetes - Kubernetes 部署:获取可用且最新的 pod 数量
- azure-ad-b2c - Azure AD B2C 自动注销 - 使用 PKCE 的授权代码流 - 自定义策略 - msal
- javascript - 具有数组和对象的函数
- python - 从python中的每个组中获取前n个值?
- c# - 为什么 UserClaims 没有添加到 Asp.net 核心身份流中的身份验证 cookie
- html - 如何在不拉伸的情况下将图像调整为工具栏中的父元素?
- qt5 - 与桌面应用程序和 WebAssembly 应用程序不同的行为
- javascript - 反应原生错误的后退按钮行为
- angular - 命名路由器出口匹配但保持为空