Format

Table of Contents

Format a number as percent howto

scales::percent(0.95)
[1] "95%"

Format a number with commas howto

format(12345678, big.mark = ",", scientific = FALSE)
[1] "12,345,678"

Format numbers in a vector individually howto

I could not find an elegant way to do this. You have to format each element separated with sapply(). As a side effect, it convert the original vector into a char vector.

x <- c(1, 0.1, 0.0001, 1e-10)
x
[1] 1e+00 1e-01 1e-04 1e-10
sapply(x, format)
[1] "1"     "0.1"   "1e-04" "1e-10"

sprintf(fmt, ...) reference

sprintf("%f", pi)
sprintf("%.3f", pi)
sprintf("%1.0f", pi)
sprintf("%5.1f", pi)
sprintf("%05.1f", pi)
sprintf("%+f", pi)
sprintf("% f", pi)
sprintf("%-10f", pi) # left justified
sprintf("%e", pi)
sprintf("%E", pi)
sprintf("%g", pi)
sprintf("%g",   1e6 * pi) # -> exponential
sprintf("%.9g", 1e6 * pi) # -> "fixed"
sprintf("%G", 1e-6 * pi)
[1] "3.141593"
[1] "3.142"
[1] "3"
[1] "  3.1"
[1] "003.1"
[1] "+3.141593"
[1] " 3.141593"
[1] "3.141593  "
[1] "3.141593e+00"
[1] "3.141593E+00"
[1] "3.14159"
[1] "3.14159e+06"
[1] "3141592.65"
[1] "3.14159E-06"