[Rd] Commas in formatC

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Fri, 22 Mar 2002 12:15:20 +0100

>>>>> "JonR" == Jonathan Rougier <J.C.Rougier@durham.ac.uk> writes:

    JonR> Martin Maechler wrote:
    >>  >>>>> "DavidB" == David Brahm <brahm@alum.mit.edu>
    >> writes:
    DavidB> formatC() is great for formatting numbers!  But it
    DavidB> would be even better if it could optionally insert
    DavidB> commas (or semicolons), e.g.
    R> formatC(1234567.89, digits=2, format="f", commas=T)
    DavidB> [1] "1,234,567.89"
    DavidB> Here's a snippet of code that does that, which could
    DavidB> more or less just be inserted into at the end of
    DavidB> formatC if any R-core guru were so inclined.  "r" is
    DavidB> the result so far, and "commas" is a logical flag:
    DavidB> stp <- regexpr("[0-9]+", r); len <- attr(stp,
    DavidB> "match.length") if (commas && (maxl <- max(len)) >
    DavidB> 3) for (i in seq(3, maxl-1, 3)) r[len>i] <-
    DavidB> paste(substring(r[len>i], 1, (stp+len-1-i)[len>i]),
    DavidB> substring(r[len>i], (stp+len-i)[len>i]), sep=",")
    >>  Thank you, David, for the suggestion.
    >> I'm looking at adding something quite a bit more general
    >> to both format.default() and formatC(), using a new
    >> function prettyNum() and using new arguments (that are
    >> compatible to S-plus' format.default).

(in the mean time available in R-devel's snapshot of last night)

    JonR> Hi Martin,

    JonR> Maybe this is a step in the wrong direction, but I
    JonR> actually like using C string formatting, eg I would
    JonR> like to be able to type something like

    JonR>   str <- stringC("The man called %s is %i feet tall", "Sven", 6)

    JonR> which is also used in Python via the string formatting
    JonR> operator, '%'.  Is this a possibility?

of course. But just a ``nice to have'' possibility.
If we had it, I'd probably rather call it sprintf(.....) though.

This should be a nice exercise to solve with  .External()
{so we could switch it to .Internal(..) easily},
using C's  sprintf() -- the most tricky part might be to pass an
arbitrary number of arguments to sprintf().

Submissions are welcome... ;-)

Martin Maechler <maechler@stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch