String Padding and Alignment
Use formatC() and format() for fixed-width and aligned text output.
Why String Padding Matters
Fixed-width output is essential for plain-text tables, log files, and reports. R provides formatC() and format() for padding values to a fixed width, ensuring columns align correctly in monospace displays.
# Unformatted: columns misalign
cat('Alice 85\n')
cat('Bob 9200\n')
# Padded: columns align
cat(formatC('Alice', width = 10), formatC(85, width = 6), '\n')
cat(formatC('Bob', width = 10), formatC(9200, width = 6), '\n')formatC() — Right-Aligned Padding
formatC(x, width = n) pads the value to at least n characters wide, right-aligning by default. Spaces are added on the left. This works for both numbers and strings.
formatC('hi', width = 10)
formatC(42, width = 10)
formatC(3.14, width = 10)