This function takes a set of options for the format() function and returns a function that itself calls format() with those settings.

formatfunc(
  percent = FALSE,
  prefix = "",
  suffix = "",
  scale = 1,
  digits = NULL,
  nsmall = 0L,
  big.mark = "",
  trim = TRUE,
  scientific = FALSE,
  ...
)

Arguments

percent

Whether to apply percentage formatting. Set to TRUE if 1 = 100%. Or, optionally, set to any other number that represents 100%. So percent = TRUE or percent = 1 will interpret .9 as 90%, or percent = 100 will format 90 as 90%.

prefix

A prefix to apply to the formatted number. For example, prefix = '$' would format 4 as $4.

suffix

A suffix to apply to the formatted number. If specified alongside percent, the suffix comes after the %.

scale

A scalar value to be multiplied by all numbers prior to formatting. scale = 1/1000, for example, would convert the units into thousands. This is applied before digits.

digits

Number of significant digits.

nsmall

The minimum number of digits to the right of the decimal point.

big.mark

A character to mark thousands places, for example producing "1,000" instead of "1000".

trim

Whether numbers should be trimmed to their own size, rather than being right-justified to a common width. Unlike the actual format(), this defaults to TRUE. Note that in most vtable applications, the formatting function is applied one value at a time, rather than to a vector, so trim = FALSE may not work as intended.

scientific

Whether numbers should be encoded in scientific format. Unlike the actual format(), this defaults to FALSE.

...

Arguments to be passed to format(). See help(format). All other parameters listed above except for percent, prefix, or suffix are also just part of format, but may be of particular interest, or have been included to show how defaults have changed.

Details

The only differences are:

1. scientific is set to FALSE by default, and trim is set to TRUE 2. Passing a NA value produces '' instead of 'NA'. 3. In addition to standard format() options, it also accepts a percent option to apply percentage formatting, and prefix and suffix options to apply prefixes or suffixes to formatted numbers. 4. Has an attribute 'big.mark' storing the 'big.mark' option chosen.

This is in the spirit of the label_ functions in the scales package, except that it uses format()'s focus on significant digits instead of fixed decimal places, which is good for numbers that range across multiple orders of magnitude, common in sumtable() and vtable().

Examples

x <- c(1, 1000, .000235, 1298.255, NA)
my.formatting.func = formatfunc(digits = 3, prefix = '$')
my.formatting.func(x)
#> [1] "$1.000000"    "$1000.000000" "$0.000235"    "$1298.255000" ""