Learn R Programming

Hmisc (version 5.3-1)

unicodeSN: Format Numbers in Scientific Notation Using Unicode Superscripts

Description

Converts numbers to compact scientific notation such as `1.5x10^-4` using the unicode symbol for the multiplication sign and unicode superscript characters for the exponent so that the result needs no LaTeX or markdown math and occupies little space in a Quarto (or R Markdown) report. Trailing zeros in the coefficient are removed (`2.00x10^3` becomes `2x10^3`). Numbers of moderate magnitude are not put in scientific notation; they are simply rounded and formatted.

Usage

unicodeSN(x, digits = 2, bounds = c(0.001, 100))

Value

a character vector of the same length as `x`.

Arguments

x

numeric vector.

digits

maximum number of digits to the right of the decimal point in the coefficient (default 2). Numbers that are not converted to scientific notation are shown with `digits + 1` significant digits, i.e., the same precision as the coefficient.

bounds

two-element numeric vector `c(lower, upper)` (default `c(0.001, 100)`). Numbers with `lower <= abs(x) < upper`, and zero, are shown in ordinary notation instead of scientific notation.

Author

Frank Harrell

Details

If `x` is zero, or if `bounds[1] <= abs(x) < bounds[2]`, the result is the number rounded and formatted with `format()` instead of scientific notation. All other finite values are written as `coefficient×10^exponent` with a coefficient whose absolute value is at least 1 and less than 10. `NA` is returned as `NA`, and `Inf`/`-Inf`/`NaN` are returned as their usual text.

Rounding in the non-scientific range uses significant digits (`signif(x, digits + 1)`) rather than `round(x, digits)` so that values such as 0.0012 are not displayed as 0.

Examples

Run this code
unicodeSN(c(123456, 0.000123, 1500, 2e10, -0.00045, 3.14159, 0, 0.05, 42.678))
unicodeSN(299792458, digits = 4)
unicodeSN(9.999e5)        # rounds up to 1x10^6
unicodeSN(c(0.5, 50, 5000), bounds = c(1, 1000))
# In Quarto, inline code such as `r unicodeSN(p)` needs no special chunk options

Run the code above in your browser using DataLab