The vec_fmt_bytes() function

Let’s create a numeric vector for the next few examples:

num_vals <- c(3.24294e14, 8, 1362902, -59027, NA)

Using vec_fmt_bytes() with the default options will create a character vector with values in bytes. 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_bytes(num_vals)
[1] "324.3 TB" "8 B"      "1.4 MB"   "−59 kB"   "NA"      
#> [1] "324.3 TB" "8 B" "1.4 MB" "-59 kB" "NA"

We can change the number of decimal places with the decimals option:

vec_fmt_bytes(num_vals, decimals = 2)
[1] "324.29 TB" "8 B"       "1.36 MB"   "−59.03 kB" "NA"       
#> [1] "324.29 TB" "8 B" "1.36 MB" "-59.03 kB" "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_bytes(num_vals, locale = "fi")
[1] "324,3 TB" "8 B"      "1,4 MB"   "−59 kB"   "NA"      
#> [1] "324,3 TB" "8 B" "1,4 MB" "-59 kB" "NA"

Should you need to have positive and negative signs on each of the output values, use force_sign = TRUE:

vec_fmt_bytes(num_vals, force_sign = TRUE)
[1] "+324.3 TB" "+8 B"      "+1.4 MB"   "−59 kB"    "NA"       
#> [1] "+324.3 TB" "+8 B" "+1.4 MB" "-59 kB" "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_bytes(num_vals, pattern = "[{x}]")
[1] "[324.3 TB]" "[8 B]"      "[1.4 MB]"   "[−59 kB]"   "NA"        
#> [1] "[324.3 TB]" "[8 B]" "[1.4 MB]" "[-59 kB]" "NA"