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. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
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-alignsformatC(x, format='f', digits=2)for fixed decimal;'e'for scientificformat(x, justify='left'/'right'/'centre')for generic alignmentformat(x, big.mark=',', nsmall=2)for thousands separators and trailing decimalsstrrep(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')Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “String Padding and Alignment” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “String Padding and Alignment”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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
- Building Strings with paste() and paste0()
- Formatted Output with sprintf()
- Displaying Output with cat() and print()
- String Padding and Alignment