Search code examples
rnegative-number

Formatting negative numbers with brackets


I would like to format my negative numbers in "Accounting" format, i.e. with brackets. For example, I would like to format -1000000 as (1,000,000).

I know the way of introducing thousands-separator:

 prettyNum(-1000000, big.mark=",",scientific=F)

However, I am not sure how to introduce the brackets. I would like to be able to apply the formatting to a whole vector, but I would want only the negative numbers to be affected. Not that after introducing the thousands separator, the vector of numbers is now a characater vector, example:

 "-50,000" "50,000"  "-50,000" "-49,979" "-48,778" "-45,279" "-41,321"

Any ideas? Thanks.


Solution

  • A very easy approach is using paste0 and sub. Here's a simple function for this:

    my.format <- function(num){
      ind <- grepl("-", num)
      num[ind] <-  paste0("(", sub("-", "", num[ind]), ")")
      num
    }
    
    > num <- c("-50,000", "50,000",  "-50,000", "-49,979", "-48,778", "-45,279", "-41,321")
    > my.format(num)
    [1] "(50,000)" "50,000"   "(50,000)" "(49,979)" "(48,778)" "(45,279)" "(41,321)"
    

    If you want to reverse the situation, let's say, you have a vector like this:

    num2 <- my.format(num)
    

    and you want to replace (·) by -, then try

    sub(")", "", sub("\\(", "-", num2))