scales::percent_format()

Function of the Week⚖️:percent

scales::label_percent()and scales::percent_format(scale = 1)’

In this document, I will introduce the `scales::label_percent() and The percent() function .

library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.1.1     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(scales)
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
library(dplyr)
library(ggplot2)
library(palmerpenguins)
data("penguins")

What is it for?

percent () is a function from an old interface. The percent() function formats numbers as percentages and can allow for accurate decimal places.Percent_format is a generalized version of percent(). Label_percent is used to create percentage_format labels on ggplots.

sex1<-penguins %>%
  count(sex) %>%
  mutate(pct= n/sum(n))%>%
print()
## # A tibble: 3 x 3
##   sex        n    pct
##   <fct>  <int>  <dbl>
## 1 female   165 0.480 
## 2 male     168 0.488 
## 3 <NA>      11 0.0320
sex1 %>%
  ggplot(aes(sex, pct)) +
  geom_col()+
  scale_y_continuous(labels=scales::label_percent())

`scales::label_percent()’is useful , especially if you have not created the percentage (multiplied by 100 ) in the mutate function. I do not think there is any other way to create the labels as a percentage unless you change the axis titles using labs(), but that would only change the title of the axis not the values to a percentage. Percent_format is useful as well, you could create percentages by mutating and creating a new function and variable, but that has more coding steps and unnecessary.I think defining the accuracy and significant figures is helpful as well.

pct1 <- scales::percent_format(scale = 1)
pct1(100)
## [1] "100%"
data <- c(.3, .7, .14, .18, .22, .78)
percent(data, accuracy = 1)
## [1] "30%" "70%" "14%" "18%" "22%" "78%"
percent(data, accuracy = 0.1)
## [1] "30.0%" "70.0%" "14.0%" "18.0%" "22.0%" "78.0%"

Is it helpful?

Yes, I think label_percent is useful when creating a ggplot.Percent and percent format are also useful, it is more efficient than creating a mutate function.The percent_format() and Percent()can provide an accurate number which is useful.