Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (5.3k points)
edited by

One of the things that used to perplex me as a newbie 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 "newbie 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.

1 Answer

0 votes
by
edited by

To format a number as a percentage in R, you can use the percent function from the scales package as follows:

> percent((5:15) / 100)

 [1] "5.0%"  "6.0%"  "7.0%"  "8.0%"  "9.0%"  "10.0%" "11.0%" "12.0%" "13.0%" "14.0%"

[11] "15.0%"

> percent((-1:5)/100)

[1] "-1.00%" "0.00%"  "1.00%"  "2.00%"  "3.00%"  "4.00%"  "5.00%" 

> percent((10:20) / 1000)

 [1] "1.00%" "1.10%" "1.20%" "1.30%" "1.40%" "1.50%" "1.60%" "1.70%" "1.80%" "1.90%"

[11] "2.00%"

> percent((1:10) / 100000)

 [1] "0.00100%" "0.00200%" "0.00300%" "0.00400%" "0.00500%" "0.00600%" "0.00700%"

 [8] "0.00800%" "0.00900%" "0.01000%"

> percent(sqrt(seq(1, 2, by=0.1)))

 [1] "100.0%" "104.9%" "109.5%" "114.0%" "118.3%" "122.5%" "126.5%" "130.4%" "134.2%"

[10] "137.8%" "141.4%"

> percent(seq(0, 0.2, by=0.02) ** 5)

 [1] "0.0000%" "0.0000%" "0.0000%" "0.0001%" "0.0003%" "0.0010%" "0.0025%" "0.0054%"

 [9] "0.0105%" "0.0189%" "0.0320%"

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...