rformatnumbersrenjin

Return a number as a comma-delimited string


Background

Due to a bug in Renjin, the format family of functions are unavailable, but sprintf works.

Code

Here is a replacement function that converts a number to a comma-delimited string:

commas <- function( n ) {
  s <- sprintf( "%03.0f", n %% 1000 )
  n <- n %/% 1000

  while( n > 0 ) {
    s <- concat( sprintf( "%03.0f", n %% 1000 ), ',', s )
    n <- n %/% 1000
  }

  gsub( '^0*', '', s )
}

Question

While the code does the job, how can the implementation be sped up? That is, how can the code be written so as to make use of R vernacular (without using format, formatC, prettyNum, and the like) and without broken Renjin packages (i.e., no dependencies)?


Solution

  • Unfortunately, a number of Renjin packages are not fully implemented, so until a fix is in place, the code in the question is a decent work around:

    commas <- function( n ) {
      s <- sprintf( "%03.0f", n %% 1000 )
      n <- n %/% 1000
    
      while( n > 0 ) {
        s <- concat( sprintf( "%03.0f", n %% 1000 ), ',', s )
        n <- n %/% 1000
      }
    
      gsub( '^0*', '', s )
    }