How to Use sprintf in R: Syntax and Examples
In R, use
sprintf() to create formatted strings by specifying a format string and values to insert. It works like a template where placeholders (like %s for strings or %d for integers) are replaced by the given values.Syntax
The sprintf() function takes a format string followed by one or more values to insert into that string. The format string contains placeholders that start with % and specify the type and format of the value.
%s: string%d: integer number%f: floating-point number%.nf: floating-point withndecimal places%x: hexadecimal
r
sprintf(fmt, ...)
# fmt: format string with placeholders
# ...: values to insertExample
This example shows how to format a string with a name, an integer age, and a floating-point score with two decimals.
r
name <- "Alice" age <- 30 score <- 95.6789 result <- sprintf("Name: %s, Age: %d, Score: %.2f", name, age, score) print(result)
Output
[1] "Name: Alice, Age: 30, Score: 95.68"
Common Pitfalls
Common mistakes include:
- Using the wrong placeholder for the data type (e.g.,
%dfor a string). - Not matching the number of placeholders with the number of values.
- Forgetting to use
print()or assign the result to see the output.
r
## Wrong: Using %d for a string sprintf("Age: %d", "thirty") ## Right: Use %s for string sprintf("Age: %s", "thirty")
Output
[1] "Age: thirty"
Quick Reference
| Placeholder | Description | Example |
|---|---|---|
| %s | String | sprintf("Hello %s", "Bob") -> "Hello Bob" |
| %d | Integer number | sprintf("Count: %d", 5) -> "Count: 5" |
| %f | Floating-point number | sprintf("Value: %f", 3.14) -> "Value: 3.140000" |
| %.nf | Floating-point with n decimals | sprintf("Pi: %.2f", 3.14159) -> "Pi: 3.14" |
| %x | Hexadecimal | sprintf("Hex: %x", 255) -> "Hex: ff" |
Key Takeaways
Use sprintf() to create formatted strings by combining a format template with values.
Match placeholders like %s, %d, and %f to the correct data types to avoid errors.
Use %.nf to control decimal places for floating-point numbers.
Always check that the number of placeholders matches the number of values provided.
Assign or print the result of sprintf() to see the formatted string.