37

I have a data frame storing the dollar amount, it looks like this

> a
  cost
1 1e+05
2 2e+05

I would like it can be shown as this

> a  
  cost
1 $100,000
2 $200,000

How to do that in R?

zx8754
  • 46,390
  • 10
  • 104
  • 180
user288609
  • 11,491
  • 24
  • 77
  • 114

4 Answers4

45
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
Roland
  • 122,144
  • 10
  • 182
  • 276
30

This will get you everything except the commas:

> 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"

Getting those is pretty complicated, as shown in these questions:

Luckily, this is implemented in the 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"
Community
  • 1
  • 1
Thomas
  • 42,067
  • 12
  • 102
  • 136
23

You can use the currency() function from the formattable package. With OP's example

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

By default, 2 digits after the decimal point are shown. This has been overruled using the digits parameter to meet OP's expectations.

The benfit of formattable is that numbers are still numbers even with a format attached, e.g.,

a$cost2 <- 2 * a$cost
a
      cost    cost2
1 $100,000 $200,000
2 $200,000 $400,000
Uwe
  • 39,148
  • 11
  • 82
  • 123
Liliana Pacheco
  • 851
  • 9
  • 12
1

A very simple way is

library(priceR)
values <- c(1e5, 2e5)
format_dollars(values)

# [1] "$100,000" "$200,000"

Notes

  • Add decimal places with format_dollars(values, 2) i.e. "$100,000.00" "$200,000.00"
  • For other currencies use format_currency(values, "€") which gives "€100,000" "€200,000" etc
stevec
  • 27,285
  • 13
  • 133
  • 181