<- c(3.24e-4, 8.65, 1362902.2, -59027.3, NA) num_vals
The vec_fmt_scientific()
function
Let’s create a numeric vector for the next few examples:
Using vec_fmt_scientific()
with the default options will create a character vector with values in scientific 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_scientific(num_vals)
[1] "3.24 × 10<sup style='font-size: 65%;'>−4</sup>"
[2] "8.65"
[3] "1.36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−5.90 × 10<sup style='font-size: 65%;'>4</sup>"
[5] "NA"
#> [1] "3.24 x 10^-4" "8.65" "1.36 x 10^6" "-5.90 x 10^4" "NA"
We can change the number of decimal places with the decimals
option:
vec_fmt_scientific(num_vals, decimals = 1)
[1] "3.2 × 10<sup style='font-size: 65%;'>−4</sup>"
[2] "8.7"
[3] "1.4 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−5.9 × 10<sup style='font-size: 65%;'>4</sup>"
[5] "NA"
#> [1] "3.2 x 10^-4" "8.7" "1.4 x 10^6" "-5.9 x 10^4" "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_scientific(num_vals, locale = "es")
[1] "3,24 × 10<sup style='font-size: 65%;'>−4</sup>"
[2] "8,65"
[3] "1,36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−5,90 × 10<sup style='font-size: 65%;'>4</sup>"
[5] "NA"
#> [1] "3,24 x 10^-4" "8,65" "1,36 x 10^6" "-5,90 x 10^4" "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_scientific(num_vals, force_sign_m = TRUE)
[1] "+3.24 × 10<sup style='font-size: 65%;'>−4</sup>"
[2] "+8.65"
[3] "+1.36 × 10<sup style='font-size: 65%;'>6</sup>"
[4] "−5.90 × 10<sup style='font-size: 65%;'>4</sup>"
[5] "NA"
#> [1] "+3.24 x 10^-4" "+8.65" "+1.36 x 10^6" "-5.90 x 10^4" "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_scientific(num_vals, pattern = "[{x}]")
[1] "[3.24 × 10<sup style='font-size: 65%;'>−4</sup>]"
[2] "[8.65]"
[3] "[1.36 × 10<sup style='font-size: 65%;'>6</sup>]"
[4] "[−5.90 × 10<sup style='font-size: 65%;'>4</sup>]"
[5] "NA"
#> [1] "[3.24 x 10^-4]" "[8.65]" "[1.36 x 10^6]" "[-5.90 x 10^4]" "NA"