我有一个存储金额的数据框,看起来像这样
> a
cost
1 1e+05
2 2e+05
我希望它可以显示为
> a
cost
1 $100,000
2 $200,000
如何在R?
中做到这一点答案 0 :(得分:32)
DF <- data.frame(cost=c(1e4, 2e5))
#assign a class
class(DF$cost) <- c("money", class(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
答案 1 :(得分:23)
这将为您提供除逗号之外的所有内容:
> 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"
获取这些内容非常复杂,如以下问题所示:
幸运的是,这是在scales package:
中实现的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"
答案 2 :(得分:15)
您可以使用currency()
包中的formattable
功能。用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
答案 3 :(得分:0)
一种非常简单的方法是
<div class="Container">
<div class="header">
<div>
<h1>Information & Advice</h1>
</div>
<div>
<h2>From The Daylight Experts</h2>
</div>
</div>
<div class="wrapper">Your wrapper content here...
<app-carousel></app-carousel>
<app-instagram></app-instagram>
<app-guides></app-guides>
</div>
</div>
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, "€")
等