fmt_num: Number formatters

View source: R/formatters.R

fmt_numR Documentation

Number formatters

Description

A set of functions to format numeric values:

  • fmt_num() is a generic formatter for numbers.

  • fmt_pct() multiply values by one hundred and display percent sign.

All formatters allow you to re-scale (multiplicatively), to round to specified accuracy, to add custom suffix and prefix and to specify decimal.mark and big.mark.

The functions were adapted directly from the scales package.

Usage

fmt_num(
  x,
  accuracy = 1,
  scale = 1,
  prefix = "",
  suffix = "",
  big.mark = "",
  decimal.mark = ".",
  trim = TRUE,
  as_numeric = FALSE,
  as_factor = FALSE,
  ...
)

fmt_pct(
  x,
  accuracy = NULL,
  scale = 100,
  prefix = "",
  suffix = "%",
  big.mark = "",
  decimal.mark = ".",
  trim = TRUE,
  ...
)

Arguments

x

A numeric vector to format.

accuracy

Number to round to, NULL for automatic guess.

scale

A scaling factor: x will be multiply by scale before formating (useful if the underlying data is on another scale, e.g. for computing percentages or thousands).

prefix, suffix

Symbols to display before and after value.

big.mark

Character used between every 3 digits to separate thousands.

decimal.mark

The character to be used to indicate the numeric decimal point.

trim

Logical, if FALSE, values are right-justified to a common width (see base::format()).

as_numeric

Logical; if TRUE, a numeric value is returned

as_factor

Logical; if TRUE, a factor is returned

...

Other arguments passed on to base::format().

Value

⁠*_format()⁠ returns a function with single parameter x, a numeric vector, that returns a character vector.

Examples

v <- c(12.3, 4, 12345.789, 0.0002)
fmt_num(v)
fmt_num(v, big.mark = ",")
fmt_num(v, accuracy = .001)
fmt_num(v, accuracy = .001, decimal.mark = ",")
fmt_num(v, accuracy = .5)

w <- c(-90.256, -0.1212, NA, NA)
fmt_num(w)
fmt_num(w, big.mark = ",")
fmt_num(w, accuracy = .001)
fmt_num(w, accuracy = .001, decimal.mark = ",")
fmt_num(w, accuracy = .5)
fmt_pct(x = runif(10))
fmt_pct(x = c(1, runif(10)), trim = FALSE)

emilelatour/lamisc documentation built on April 9, 2024, 10:33 a.m.