One of the things that used to perplex me as a newby to R was how to format a number as a percentage for printing.
For example, display 0.12345
as 12.345%
. I have a number of workarounds for this, but none of these seem to be "newby friendly". For example:
set.seed(1)
m <- runif(5)
paste(round(100*m, 2), "%", sep="")
[1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"
sprintf("%1.2f%%", 100*m)
[1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"
Question: Is there a base R function to do this? Alternatively, is there a widely used package that provides a convenient wrapper?
Despite searching for something like this in ?format
, ?formatC
and ?prettyNum
, I have yet to find a suitably convenient wrapper in base R. ??"percent"
didn't yield anything useful. library(sos); findFn("format percent")
returns 1250 hits - so again not useful. ggplot2
has a function percent
but this gives no control over rounding accuracy.
sprintf
seems to be the favorite solution on the mailing lists, and I've not seen any better solution. Any built-in function won't be much simpler to call anyway, right? – Hwusprintf
is perfectly fine for that subset of R coders that also happen to be programmers. I have coded a lot in my life, including COBOL (shudder) and fortran (shows my age). But I don't consider thesprintf
formatting rules obvious (translation: WTF?). And of course a dedicated wrapper must be easier to call than sprintf, for example:format_percent(x=0.12345, digits=2)
– Unquietsprintf()
is hardly more time consuming than finding out that package foo containsformat_percent()
. What happens if the user then doesn't want to format as percent but something else that is similar? They need to find another wrapper. In the long run learning the base tools will be beneficial. – Eyeglasses%
is the comment character in LaTeX, which is the "default" reporting format for R. So while it may be useful for labelling graphs, care must be taking if the formatted number is to be Sweaved. – Teodorateodorico