Home > front end >  how to add $ symbol in from of number
how to add $ symbol in from of number

Time:10-18

I have few numbers which is having class as numeric . example below .

df = c(12974,12412,124124,124124,34543,4576547,32235)

now I want to add '$' symbol in front of every number without losing its class as numeric .

i tried using paste method but for that I have to convert as.numeric to as.character and then after using paste function if i convert is as.numeric it returns as Na! can anyone help me ? thanks in advance !

CodePudding user response:

In general, you should leave your data as numeric while you are using it for calculations / analysis, and only paste the dollar sign when you want to present the result in a table, plot or report. Otherwise, why would you need it?

There is no built-in currency class in R, and this is probably a good thing. However, R is a flexible language that allows for quick and simple S3 class creation, so if you really wanted to, you could.

The following is a very basic implementation of such a system. It is based on an integer number of cents to avoid problems with floating point numbers:

dollars <- function(x) {
  structure(as.integer(x * 100), class = "dollars")
}

as.dollars <- function(x) {
  dollars(x)
}

format.dollars <- function(x, ...) {
  scales::dollar(round(unclass(x)/100, 2))
}

print.dollars <- function(x, ...) {
  print(format(x), quote = FALSE, ...)
}

as.data.frame.dollars <- function(x, ...) {
  nrows <- length(x)
  structure(list(x), row.names = as.character(seq(nrows)), class = "data.frame")
}

Testing this out on your example, we have

df <- c(12974, 12412, 124124, 124124, 34543, 4576547, 32235)

as.dollars(df)
#> [1] $12,974    $12,412    $124,124   $124,124   $34,543    $4,576,547 $32,235

And we can store the result in a data frame:

dat <- data.frame(cost = as.dollars(df))

dat
#>         cost
#> 1    $12,974
#> 2    $12,412
#> 3   $124,124
#> 4   $124,124
#> 5    $34,543
#> 6 $4,576,547
#> 7    $32,235

and perform arithmetic while maintaining its dollar sign.

dat$cost / 2
#> [1] $6,487     $6,206     $62,062    $62,062    $17,272    $2,288,274 $16,118

I personally don't think this is worth the effort, and certainly wouldn't use it in production code, but hopefully it gives you some ideas.

Created on 2022-10-17 with reprex v2.0.2

  •  Tags:  
  • r
  • Related