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.
An update, several years later:
These days there is a
percent
function in thescales
package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.Try something like
With usage, e.g.,
(If you prefer, change the format from
"f"
to"g"
.)I did some benchmarking for speed on these answers and was surprised to see
percent
in thescales
package so touted, given its sluggishness. I imagine the advantage is its automatic detector for for proper formatting, but if you know what your data looks like it seems clear to be avoided.Here are the results from trying to format a list of 100,000 percentages in (0,1) to a percentage in 2 digits:
So
sprintf
emerges as a clear winner when we want to add a percent sign. On the other hand, if we only want to multiply the number and round (go from proportion to percent without "%", thenround()
is fastest:This function could transform the data to percentages by columns
Here's my solution for defining a new function (mostly so I can play around with Curry and Compose :-) ):
Check out the
scales
package. It used to be a part ofggplot2
, I think.The built-in logic for detecting the precision should work well enough for most cases.
Check out the
percent
function from theformattable
package: