Print a Formatted string in R Programming - sprintf() Function
The sprintf()
function is used to create formatted strings in R. These formatted strings enable us to insert variables and values into a string while controlling their appearance and formatting. The sprintf()
function uses a user-defined format to return a formatted string by inserting the corresponding values from the provided list.
Syntax :
sprintf(format, values)
Parameter:
- format: Format of printing the values
- values: to be passed into format
Example 1:
In the given R program, sprintf()
is used to create a formatted string. The format string " % s to % s"
contains two %s
placeholders, which are meant for string values. The variables x1
and x2
are inserted into these placeholders, resulting in the formatted string "Welcome to GeeksforGeeks". sprintf()
replaces the placeholders with the values of x1
and x2
, allowing for dynamic and structured string formatting.
x1 <- "Welcome"
x2 <- "GeeksforGeeks"
sprintf("% s to % s", x1, x2)
Output:
"Welcome to GeeksforGeeks"
Example 2:
In the given R program, sprintf()
is used to create a formatted string. The format string "%s gives %.0f percent %s"
contains three placeholders: %s
for strings and %.0f
for a formatted number (percentage). The variables x1
, x2
, and x3
are inserted into these placeholders. The value of x1
("GeeksforGeeks") replaces the first %s
, the value of x2
(100) is formatted as a whole number for %.0f
, and the value of x3
("success") replaces the last %s
.
x1 <- "GeeksforGeeks"
x2 <- 100
x3 <- "success"
sprintf("% s gives %.0f percent % s", x1, x2, x3)
Output:
"GeeksforGeeks gives 100 percent success"
Example 3:
In the given R program, sprintf()
is used to create a formatted string. The format string "The mean is %.2f, and the standard deviation is %.2f"
contains two %.2f
placeholders, which are used to format the numeric values mean_value
and standard_deviation
to two decimal places. The mean_value
(35.68) and standard_deviation
(7.42) are inserted into these placeholders, resulting in the formatted string
mean_value <- 35.68
standard_deviation <- 7.42
formatted_string <- sprintf("The mean is %.2f, and the standard deviation is %.2f",
mean_value, standard_deviation)
cat(formatted_string)
Output:
The mean is 35.68, and the standard deviation is 7.42
In this article, we explored how to create formatted strings in R using the sprintf()
function.