sprintf()
sprintf(fmt, ...) sprintf() formats strings using C-style format specifiers. It takes a format string containing placeholders and substitutes values into them.
Syntax
sprintf(fmt, ...)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
fmt | character | , | Format string containing format specifiers |
... | any | , | Values to substitute into the format string |
Format specifiers
The key format specifiers are:
| Specifier | Meaning | Example |
|---|---|---|
%s | String | "%s" |
%d | Integer | "%d" |
%f | Fixed-point number | "%.2f" |
%e | Scientific notation | "%e" |
%% | Literal percent sign | "%%" |
Examples
Basic string substitution
sprintf("Hello, %s!", "World")
# [1] "Hello, World!"
name <- "Alice"
sprintf("Welcome, %s!", name)
# [1] "Welcome, Alice!"
Numeric formatting
sprintf() shines when you need consistent decimal places or field widths across multiple numbers. The %f specifier prints fixed-point notation, and adding a precision like %.3f controls exactly how many digits appear after the decimal point. This avoids the inconsistency of print() or cat(), where the display format depends on the number’s magnitude.
sprintf("The value is %d", 42)
# [1] "The value is 42"
sprintf("Pi to 3 decimals: %.3f", pi)
# [1] "Pi to 3 decimals: 3.142"
sprintf("Scientific: %e", 1234)
# [1] "Scientific: 1.234000e+03"
Multiple values
Format strings can contain any number of placeholders, and sprintf() fills them from left to right using the arguments that follow fmt. When you mix types — a string here, an integer there, a float with two decimals — the format string is a compact template that keeps the output consistent regardless of the input values.
sprintf("%s has %d points", "Player", 100)
# [1] "Player has 100 points"
sprintf("Item: %s, Price: $%.2f, Qty: %d", "Widget", 19.99, 5)
# [1] "Item: Widget, Price: $19.99, Qty: 5"
Padding and width
Width specifiers inside the format string control alignment and zero-padding. A number between % and the type letter sets the minimum field width: %10s right-aligns a string in a 10-character column, and %05d pads an integer to 5 digits with leading zeros. These controls are what make sprintf() the right tool for fixed-width reports and log files.
sprintf("%10s", "test")
# [1] " test"
sprintf("%05d", 42)
# [1] "00042"
Common patterns
Building file paths
sprintf() is a practical alternative to paste0() when you are constructing file names with a known pattern. The format string makes the template explicit — "%s.%s" says “take two strings and join them with a dot” — and the arguments fill the slots in order. This reads more clearly than paste0(filename, ".", extension).
filename <- "data"
extension <- "csv"
sprintf("%s.%s", filename, extension)
# [1] "data.csv"
Creating messages
When you need to report progress — how many items processed, what percentage is complete — sprintf() lets you write the message template once and substitute the numbers in. The %.1f format keeps the percentage to one decimal place, producing clean output like “Processed 150 of 500 items (30.0%)” without awkward floating-point tails.
n <- 150
total <- 500
sprintf("Processed %d of %d items (%.1f%%)", n, total, n/total*100)
# [1] "Processed 150 of 500 items (30.0%)"
Dynamic labels
Zero-padding with %03d is the standard way to produce iteration counters that sort correctly as strings. Three-digit padding means iteration 5 becomes “005”, iteration 42 becomes “042”, and all labels stay the same width — important when you are naming files, plot titles, or log entries that will be read by both humans and scripts.
sprintf("Iteration %03d complete", 5)
# [1] "Iteration 005 complete"
sprintf() formatting codes
sprintf() follows C printf conventions. The most commonly used format codes:
%s, string%d, integer%f, fixed-point floating number%.2f, fixed-point with 2 decimal places%e, scientific notation (1.23e+05)%g, whichever of%fand%eis shorter%05d, integer padded to 5 characters with leading zeros%-10s, string left-aligned in 10-character field
sprintf() is vectorized over its arguments: sprintf("Item %d: %s", 1:3, letters[1:3]) produces three formatted strings. The function recycles shorter arguments to match the longest.
For internationalized applications, sprintf() supports reordering arguments with %1$s, %2$d notation, allowing translated format strings to rearrange elements without code changes.
sprintf() format codes and usage
sprintf() implements C-style format strings. The common format codes are: %s for strings, %d for integers, %f for fixed-point doubles (default 6 decimal places), %e for scientific notation, %g for the shorter of %f or %e, and %% for a literal percent sign.
Width and precision are specified as %[width].[precision][type]: %8.2f formats a number in 8 characters wide with 2 decimal places. Leading zeros use %08.2f. Left-alignment uses %-8s. These formatting controls make sprintf() the right tool for aligning numbers in text output, generating fixed-width fields, and building display strings with consistent formatting.
sprintf() is vectorized over its arguments: when fmt is a scalar and the value arguments are vectors, it returns a character vector of the same length. sprintf("Item %d: %s", 1:3, c("a","b","c")) returns three formatted strings. When fmt is also a vector, it must match the length of the value arguments.
For internationalization, sprintf() does not support locale-aware number formatting (thousands separators, decimal comma). Use format() with big.mark and decimal.mark arguments for locale-sensitive number display. sprintf() is for structured template substitution; format() is for locale-aware presentation.
sprintf() uses C-style format strings: %d for integers, %f for floats, %s for strings, %e for scientific notation. Width and precision are specified as %8.2f — 8 characters wide, 2 decimal places. It is vectorized: when the format or any argument is a vector, it recycles to the longest and returns a character vector. Prefer sprintf() over paste() when you need precise numeric formatting.