Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent numeric value with typical dollar amount format

Tags:

r

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?

like image 290
user288609 Avatar asked Feb 27 '14 13:02

user288609


People also ask

What format is used for dollar amounts?

United States (U.S.) currency is formatted with a decimal point (.) as a separator between the dollars and cents. Some countries use a comma (,) instead of a decimal to indicate that separation.

How do I format numbers to dollars in Excel?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.


2 Answers

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 
like image 185
Roland Avatar answered Sep 22 '22 08:09

Roland


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:

  • How can I format currency with commas in C?
  • How to format a number from 1123456789 to 1,123,456,789 in C?

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" 
like image 27
Thomas Avatar answered Sep 21 '22 08:09

Thomas