| as_percent | R Documentation |
percent is a lightweight S3 class allowing for pretty
printing of proportions as percentages.
It aims to remove the need for creating character vectors of percentages.
as_percent(x, digits = 2)
NA_percent_
x |
|
digits |
|
The rounding for percent vectors differs to that of base R rounding,
namely in that halves are rounded up instead of rounded to even.
This means that round(x) will round the percent vector x using
halves-up rounding (like in the janitor package).
By default all percentages are formatted to 2 decimal places which can be
overwritten using format() or using round() if your required digits are
less than 2. It's worth noting that the digits argument in
format.percent uses decimal rounding instead of the usual
significant digit rounding that format.default() uses.
An object of class percent.
# Convert proportions to percentages
as_percent(seq(0, 1, 0.1))
# You can use round() as usual
p <- as_percent(15.56 / 100)
round(p)
round(p, digits = 1)
p2 <- as_percent(0.0005)
signif(p2, 2)
floor(p2)
ceiling(p2)
# We can do basic math operations as usual
# Order of operations doesn't matter
10 * as_percent(c(0, 0.5, 2))
as_percent(c(0, 0.5, 2)) * 10
as_percent(0.1) + as_percent(0.2)
# Formatting options
format(as_percent(2.674 / 100), digits = 2, symbol = " (%)")
# Prints nicely in data frames (and tibbles)
library(dplyr)
starwars %>%
count(eye_color) %>%
mutate(perc = as_percent(n / sum(n))) %>%
arrange(desc(perc)) %>% # We can do numeric sorting with percent vectors
mutate(perc_rounded = round(perc))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.