This function maps over a vector of labels, such as those returned by base::cut
. It works well in formatting ggplot
scales, and can optionally pass parameters to an underlying call to base::formatC
. Any NA
values will be retained.
Usage
brk_labels(
x,
format = NULL,
custom = FALSE,
mult_by = 1,
round_digits = NULL,
sep = " to ",
...
)
Arguments
- x
A character vector.
- format
A function for formatting text, a string giving desired output format, or
NULL
(the default) for no formatting. Built-in shorthands are"percent"
,"dollar"
, and"dollark"
, the last of which formats numbers like$12.3k
. Alternatively, provide a character argument to be used bybase::formatC
and setcustom = TRUE
.- custom
Logical, whether to use custom formatting, triggering a call to
formatC
with the arguments supplied toformat
and...
. DefaultsFALSE
.- mult_by
A number by which to multiply values in breaks. Defaults to 1, i.e. just the numbers input. Note that multiplication is carried out before rounding and formatting.
- round_digits
If not
NULL
(the default), the number of digits to round to. Note that this takes place after multiplying bymult_by
.- sep
A string by which to separate values in breaks.
- ...
Any additional arguments to pass on to the function given in
format
, or tobase::formatC
ifcustom
isTRUE
.
Examples
percentage_brks <- c("[0.04,0.15]", "(0.15,0.25]", "(0.25,0.4]")
brk_labels(percentage_brks)
#> [1] "0.04 to 0.15" "0.15 to 0.25" "0.25 to 0.4"
brk_labels(percentage_brks, format = "percent", mult_by = 100)
#> [1] "4 to 15%" "15 to 25%" "25 to 40%"
scientific_brks <- c("[-15500,0]", "(0,20000]", "(20000,25000]")
brk_labels(scientific_brks, format = "e", custom = TRUE, digits = 2)
#> [1] "-1.55e+04 to 0.00e+00" "0.00e+00 to 2.00e+04" "2.00e+04 to 2.50e+04"
brk_labels(scientific_brks, format = stringr::str_pad, side = "left", pad = "0", width = 3)
#> [1] "-15500 to 000" "000 to 20000" "20000 to 25000"