0
0
R Programmingprogramming~5 mins

String formatting with sprintf in R Programming

Choose your learning style9 modes available
Introduction
String formatting with sprintf helps you create neat and readable text by inserting values into a template.
When you want to show numbers with a fixed number of decimal places.
When you need to combine text and numbers in a clear sentence.
When you want to align text or numbers in columns.
When you want to format dates or times in a specific way.
When you want to prepare messages for reports or user display.
Syntax
R Programming
sprintf(format, ...)
The format is a string that tells how to insert values, using placeholders like %s for text, %d for integers, and %f for floating-point numbers.
You can control width, precision, and alignment inside the format string.
Examples
Inserts the text 'Alice' into the placeholder %s.
R Programming
sprintf("Hello %s!", "Alice")
Inserts the integer 5 into the placeholder %d.
R Programming
sprintf("You have %d new messages.", 5)
Formats the number 3.14159 to show 2 decimal places.
R Programming
sprintf("Pi is approximately %.2f.", 3.14159)
Left-aligns 'Item' in 10 spaces and right-aligns 42 in 5 spaces.
R Programming
sprintf("%-10s %5d", "Item", 42)
Sample Program
This program creates a message greeting Bob and showing his score rounded to one decimal place.
R Programming
name <- "Bob"
score <- 87.456
message <- sprintf("Hello %s, your score is %.1f.", name, score)
print(message)
OutputSuccess
Important Notes
If you use the wrong placeholder for a value type, sprintf may give an error or unexpected result.
You can use %% to print a literal percent sign in the output.
sprintf returns the formatted string; it does not print it unless you use print() or cat().
Summary
sprintf helps build strings by inserting values into a template.
Use placeholders like %s, %d, and %f to control how values appear.
It is useful for making messages, reports, and aligned text.