0Pricing
R Academy · Lesson

String Padding and Alignment

Use formatC() and format() for fixed-width and aligned text output.

String Padding and Alignment is a free R Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)

formatC() Left-Alignment with flag

The flag = '-' argument switches to left-alignment, padding the right side with spaces. This is ideal for string labels in table columns where you want values to start at the left edge.

items <- c('Pen', 'Notebook', 'Stapler')
prices <- c(1.5, 4.99, 7.25)
for (i in seq_along(items)) {
  cat(formatC(items[i], width = 12, flag = '-'),
      formatC(prices[i], format = 'f', digits = 2, width = 8),
      '\n')
}

formatC() with Numeric Formats

formatC() supports format codes: 'f' for fixed decimal, 'e' for scientific, 'g' for the shorter of the two, and 'd' for integer. The digits argument controls precision.

x <- 12345.6789
formatC(x, format = 'f', digits = 2)
formatC(x, format = 'e', digits = 3)
formatC(x, format = 'g', digits = 5)
formatC(42L, format = 'd', width = 8)

format() — Base R Alignment

format(x, width = n, justify = 'left'/'right'/'centre') is the generic alignment function. It works on any R object and returns a character vector of equal-width strings. The default justification for numbers is right, for strings is left.

words <- c('cat', 'elephant', 'ox')
format(words, width = 10)
format(words, width = 10, justify = 'right')

format() for Numeric Precision

format() also controls decimal places with nsmall (minimum digits after decimal) and big.mark for thousands separators. These are ideal for displaying financial figures.

format(1234567.8,  big.mark = ',', nsmall = 2)
format(0.1,        nsmall = 4)
format(c(1.5, 100, 0.005), nsmall = 3)

strrep() — Repeating Strings

strrep(x, times) repeats a string a given number of times. Use it to build separator lines, padding strings, or visual decorators without manually concatenating characters.

strrep('-', 40)
strrep('=-', 20)
strrep(c('ab', 'cd'), c(3, 2))
# Draw a simple table border
cat(strrep('=', 30), '\n')

Building a Fixed-Width Text Table

Combine formatC() with cat() and strrep() to build a clean plain-text table. This pattern is common in CLI tools and log files.

header <- paste0(formatC('Name',  width=12,flag='-'),
                 formatC('Score', width=8,flag='-'),
                 formatC('Grade', width=8,flag='-'))
cat(header, '\n')
cat(strrep('-', 28), '\n')
row1 <- paste0(formatC('Alice',  width=12,flag='-'),
               formatC(92,width=8),formatC('A',width=8,flag='-'))
cat(row1, '\n')

formatC() vs sprintf() for Padding

Both formatC() and sprintf() can produce padded output. sprintf() is more concise for simple cases; formatC() is more flexible for applying the same formatting to a whole vector.

x <- 42
# sprintf approach
sprintf('%10d', x)
sprintf('%-10s', 'hello')
# formatC approach
formatC(x,       width = 10)
formatC('hello', width = 10, flag = '-')

Scientific Notation Control

formatC(x, format='e', digits=n) or options(scipen=999) controls when R switches to scientific notation. The scipen option is a penalty; larger values suppress scientific notation for longer before switching.

# Default scipen
print(0.0001234)
print(1234567890)
# Force scientific
formatC(0.0001234, format = 'e', digits = 3)
# Suppress scientific globally
old <- options(scipen = 999)
print(0.0001234)
options(old)

Practical: Padding IDs and Labels

A common need is zero-padded IDs or left-padded labels in reports. formatC() handles both: use flag = '0' for zero-padding numbers and flag = '-' for left-aligned strings.

ids    <- c(1, 12, 123)
names  <- c('Alice', 'Bob', 'Carol')
scores <- c(88.5, 91.0, 76.25)
for (i in seq_along(ids)) {
  cat(formatC(ids[i], width=5, format='d', flag='0'),
      formatC(names[i], width=10, flag='-'),
      formatC(scores[i], width=8, format='f', digits=2),
      '\n')
}

Quick Check

Which argument to formatC() makes the output left-aligned within the specified width?

Padding and Alignment: Key Takeaways

Key takeaways for string padding and alignment:

  • formatC(x, width=n) right-pads to width n; flag='-' left-aligns
  • formatC(x, format='f', digits=2) for fixed decimal; 'e' for scientific
  • format(x, justify='left'/'right'/'centre') for generic alignment
  • format(x, big.mark=',', nsmall=2) for thousands separators and trailing decimals
  • strrep(s, n) repeats a string n times — great for separator lines
  • Combine with cat() for plain-text table output
cat(strrep('=', 30), '\n')
cat(formatC('Item', width=12, flag='-'),
    formatC('Price', width=10), '\n')
cat(strrep('-', 30), '\n')
cat(formatC('Apple', width=12, flag='-'),
    formatC(1.99, width=10, format='f', digits=2), '\n')

Frequently asked questions

Is the “String Padding and Alignment” lesson free?

Yes — the full text of “String Padding and Alignment” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “String Padding and Alignment”?

Use formatC() and format() for fixed-width and aligned text output. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “String Padding and Alignment” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Building Strings with paste() and paste0()
  2. Formatted Output with sprintf()
  3. Displaying Output with cat() and print()
  4. String Padding and Alignment
← Back to R Academy