<- c(3.24e-4, 8.65, 1362902.2, -59027.3, NA) num_vals
The vec_fmt_engineering()
function
Let’s create a numeric vector for the next few examples:
Using vec_fmt_engineering()
with the default options will create a character vector with values engineering notation. Any NA
values remain as NA
values. The rendering context will be autodetected unless specified in the output
argument (here, it is of the "plain"
output type).
vec_fmt_engineering(num_vals)
[1] "324.00 × 10<sup style='font-size: 65%;'>−6</sup>"
[2] "8.65"
[3] "1.36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−59.03 × 10<sup style='font-size: 65%;'>3</sup>"
[5] "NA"
#> [1] "324.00 x 10^-6" "8.65" "1.36 x 10^6" "-59.03 x 10^3" "NA"
We can change the number of decimal places with the decimals
option:
vec_fmt_engineering(num_vals, decimals = 1)
[1] "324.0 × 10<sup style='font-size: 65%;'>−6</sup>"
[2] "8.7"
[3] "1.4 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−59.0 × 10<sup style='font-size: 65%;'>3</sup>"
[5] "NA"
#> [1] "324.0 x 10^-6" "8.7" "1.4 x 10^6" "-59.0 x 10^3" "NA"
If we are formatting for a different locale, we could supply the locale ID and gt will handle any locale-specific formatting options:
vec_fmt_engineering(num_vals, locale = "da")
[1] "324,00 × 10<sup style='font-size: 65%;'>−6</sup>"
[2] "8,65"
[3] "1,36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−59,03 × 10<sup style='font-size: 65%;'>3</sup>"
[5] "NA"
#> [1] "324,00 x 10^-6" "8,65" "1,36 x 10^6" "-59,03 x 10^3" "NA"
Should you need to have positive and negative signs for the mantissa component of a given value, use force_sign_m = TRUE
:
vec_fmt_engineering(num_vals, force_sign_m = TRUE)
[1] "+324.00 × 10<sup style='font-size: 65%;'>−6</sup>"
[2] "+8.65"
[3] "+1.36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−59.03 × 10<sup style='font-size: 65%;'>3</sup>"
[5] "NA"
#> [1] "+324.00 x 10^-6" "+8.65" "+1.36 x 10^6" "-59.03 x 10^3" "NA"
As a last example, one can wrap the values in a pattern with the pattern
argument. Note here that NA
values won’t have the pattern applied.
vec_fmt_engineering(num_vals, pattern = "/{x}/")
[1] "/324.00 × 10<sup style='font-size: 65%;'>−6</sup>/"
[2] "/8.65/"
[3] "/1.36 × 10<sup style='font-size: 65%;'>6</sup>/"
[4] "/−59.03 × 10<sup style='font-size: 65%;'>3</sup>/"
[5] "NA"
#> [1] "/324.00 x 10^-6/" "/8.65/" "/1.36 x 10^6/" "/-59.03 x 10^3/" "NA"