1

I am working with a bunch of large numbers. I know how to convert numbers to comma format from: Comma separator for numbers in R? . What I don't know how to do is display numbers in the console with commas without converting the class from numeric. I want to be able to see the commas so I can compare numbers when working - but need to keep the numbers as numeric to make calculations. I know you can get rid of scientific notation from:How to disable scientific notation? - but can't find an equivalent for a comma or dollar format.

MatthewR
  • 2,660
  • 5
  • 26
  • 37
  • 5
    How can you mix characters and numeric and expect it to be numeric? Just curious – Onyambu Mar 02 '18 at 17:07
  • excel manages to do this - i was hoping there was an option which would keep it as a number but display it with commas – MatthewR Mar 02 '18 at 17:08
  • 1
    if you are printing the number to the console, why does it matter what type the number is once its printed? I.e. if you have some numeric vector `x`, why does it matter to you to call `x` instead of `format(x, scientific = FALSE, big.mark = ",")`? Sure `x` becomes character before it hits the console, but I don't see how that can impinge on your results? – gfgm Mar 02 '18 at 17:23
  • 1
    same reason society decided to insert commas in numbers in the first place.. readability – Anthony Damico Mar 02 '18 at 17:44

1 Answers1

5

You could create a new method for print(), for a custom class I will call "bignum":

print.bignum <- function(x) {
    print(format(x, scientific = FALSE, big.mark = ",", trim = TRUE))
}

x <- c(1e6, 2e4, 5e8)
class(x) <- c(class(x), "bignum")

x

[1] "1,000,000"   "20,000"      "500,000,000"

x * 2

[1] "2,000,000"     "40,000"        "1,000,000,000"

y <- x + 1
y

[1] "1,000,001"   "20,001"      "500,000,001"


class(y) <- "numeric"
y

[1]   1000001     20001 500000001

For any numeric object x, if you add "bignum" to the class attribute via class(x) <- c(class(x), "bignum"), it will always print how you've described you want it to print, but should behave as a numeric otherwise, as shown above.

duckmayr
  • 16,303
  • 3
  • 35
  • 53
  • 1
    It's interesting if you try to overload "print.numeric <- ...", it only works when you call e.g. `print(3)` instead of just calling `3` straight to the shell, which would work with all other classes and print methods. Do you know why that is? – AdamO Mar 02 '18 at 17:51
  • @AdamO Not yet. I tried that as well and posted this solution since that didn't work. – duckmayr Mar 02 '18 at 17:57