R Language Printing a gmp Big Integer with Commas

Even though the R language is used for statistics and data analysis, it doesn’t have a built-in big integer type. The gmp add-on package has a big integer type named “bigz” and related functions such as factorialZ().

PrettyCatDemo

Code like:

f = factorialZ(40)
cf = as.character(f)
cat(cf)

Gives a number without commas:

265252859812191058636308480000000

I wanted to pretty-print a gmp big integer with commas. I figured there’d be existing code to do this but I couldn’t find any. So I coded up my own custom pretty print function.

pretty_cat = function(intStr) {
  x = strsplit(intStr, NULL)[[1]]
  n = length(x)
  y = rev(x)
  i = n
  while (i ≥ 1) {
    if (i != n && i %% 3 == 0) {
      cat(",")
    }
    cat(y[i])
    i = i - 1
  }
}

The code was a bit tricky – almost every line of code has a nuance or two. The moral is that because R is a huge language, it’s hard to find things and there’s a tradeoff between searching for existing code and just writing your own.

This entry was posted in R Language. Bookmark the permalink.