我有一个存储美元金额的数据框,看起来像这样
> a
cost
1 1e+05
2 2e+05
我希望它可以显示为这样
> a
cost
1 $100,000
2 $200,000
如何在 R 中做到这一点?
DF <- data.frame(cost=c(1e4, 2e5))
#assign a class
oldClass(DF$cost) <- c("money", oldClass(DF$cost))
#S3 print method for the class
print.money <- function(x, ...) {
print.default(paste0("$", formatC(as.numeric(x), format="f", digits=2, big.mark=",")))
}
#format method, which is necessary for formating in a data.frame
format.money <- function(x, ...) {
paste0("$", formatC(as.numeric(x), format="f", digits=2, big.mark=","))
}
DF
# cost
#1 $10,000.00
#2 $200,000.00
这将为您提供除逗号之外的所有内容:
> sprintf("$%.2f", seq(100,100000,by=10000)/7)
[1] "$14.29" "$1442.86" "$2871.43" "$4300.00" "$5728.57" "$7157.14" "$8585.71" "$10014.29" "$11442.86" "$12871.43"
获得这些非常复杂,如以下问题所示:
- 如何在 C 中用逗号格式化货币?
- 如何在 C 中将数字从 1123456789 格式化为 1,123,456,789?
幸运的是,这是在秤包中实现的:
library('scales')
> dollar_format()(c(100, 0.23, 1.456565, 2e3))
## [1] "$100.00" "$0.23" "$1.46" "$2,000.00"
> dollar_format()(c(1:10 * 10))
## [1] "$10" "$20" "$30" "$40" "$50" "$60" "$70" "$80" "$90" "$100"
> dollar(c(100, 0.23, 1.456565, 2e3))
## [1] "$100.00" "$0.23" "$1.46" "$2,000.00"
> dollar(c(1:10 * 10))
## [1] "$10" "$20" "$30" "$40" "$50" "$60" "$70" "$80" "$90" "$100"
> dollar(10^(1:8))
## [1] "$10" "$100" "$1,000" "$10,000" "$100,000" "$1,000,000" "$10,000,000" "$100,000,000"
您可以使用
formattable
包中的currency()
函数。以OP为例
a <- data.frame(cost = c(1e+05, 2e+05))
a
cost 1 1e+05 2 2e+05
library(formattable)
a$cost <- currency(a$cost, digits = 0L)
a
cost 1 $100,000 2 $200,000
默认情况下,显示小数点后的 2 位数字。使用digits
参数来满足OP的期望,这已被否决。
formattable
的好处是,即使附加了格式,数字仍然是数字,例如,
a$cost2 <- 2 * a$cost
a
cost cost2 1 $100,000 $200,000 2 $200,000 $400,000
一个非常简单的方法是
library(priceR)
values <- c(1e5, 2e5)
format_dollars(values)
# [1] "$100,000" "$200,000"
笔记
- 用
format_dollars(values, 2)
添加小数位,即"$100,000.00" "$200,000.00"
- 对于其他货币,请使用
format_currency(values, "€")
,以提供"€100,000" "€200,000"
等