In a previous question, I asked whether whether a convenient wrapper exists inside base R to format numbers as percentages.
This elicited three responses:
- Probably not.
- Such a wrapper would be too narrow to be useful. It is better that useRs learn how to use existing tools, such as
sprintf, which can format numbers in a highly flexible way. - Such a wrapper is problematic, anyway, since you lose the ability to perform calculations on the object.
Still, in my view the sprintf function is just a little bit too obfuscated for the R beginner to learn (except if they come from a C background). Perhaps a better solution is to modify format or prettyNum to have options for adding prefixes and suffixes, so you could easily create percents, currencies, degrees, etc.
Question:
How would you design a function, class or set of functions to elegantly deal with formatting numbers as percentages, currencies, degrees, etc?
I would probably keep things very simple.
format()is generally useful for most basic formatting needs. I would extend that with a simple wrapper that allowed arbitraryprefixandsuffixstrings. Here is a simple version:If I were doing this for real, I would probably not have the
collapseargument in the definition offormatVal(), but instead process it out of..., but for illustration I kept the above function simple.Using:
some simple examples of usage