R String Formatting
R's sprintf() and format() functions let you control exactly how numbers and text are displayed inside a string.
Templating Text with sprintf()
sprintf() builds a string from a template containing placeholders, then fills each placeholder with a value you supply — much like a fill-in-the-blank form. It borrows its placeholder syntax from the C language, so every placeholder starts with a percent sign followed by a letter describing the expected type.
- %s – insert a character string
- %d – insert a whole number
- %f – insert a decimal number
- %% – insert a literal percent sign
Example
name <- "Maria"
age <- 29
sprintf("%s is %d years old", name, age)
# "Maria is 29 years old"
price <- 19.5
sprintf("Total: $%.2f", price)
# "Total: $19.50"Controlling Width and Decimal Places
Add a number right after the percent sign to control the field width, and a decimal point followed by a digit to control precision. %05d pads a number with leading zeros up to a width of 5, while %.2f always shows exactly two digits after the decimal point.
Example
sprintf("%05d", 42)
# "00042"
sprintf("%8.2f", 3.5)
# " 3.50"Formatting Numbers for Display with format()
Where sprintf() is about building templated text, format() is about presenting a number cleanly on its own. big.mark inserts a separator (like a comma) every three digits, and nsmall guarantees a minimum number of digits after the decimal point.
Example
format(1234567, big.mark = ",")
# "1,234,567"
format(3.1, nsmall = 3)
# "3.100"