Open In App

Print a Formatted string in R Programming – sprintf() Function

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In R Programming Language we can create formatted strings using various methods, including the sprintf() function, the paste() function. Formatted strings allow us to insert of variables and values into a string while controlling their formatting. Here are some common methods for creating formatted strings in R Programming Language.

sprintf() function in R

sprintf() function in R uses Format provided by the user to return the formatted string with the use of the values in the list.

Syntax:

sprintf(format, values)

Parameter:

format: Format of printing the values

values: to be passed into format

Example 1: Formatted string in R Programming using sprintf() Function

R




# R program to illustrate
# the use of sprintf() function
 
# Initializing values
x1 <- "Welcome"
x2 <- "GeeksforGeeks"
 
# Calling sprintf() function
sprintf("% s to % s", x1, x2)


Output:

[1] "Welcome to GeeksforGeeks"

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.

Example 2: Formatted string in R Programming using sprintf() Function

R




# R program to illustrate
# the use of sprintf() function
 
# Initializing values
x1 <- "GeeksforGeeks"
x2 <- 100
x3 <- "success"
 
# Calling sprintf() function
sprintf("% s gives %.0f percent % s", x1, x2, x3)


Output:

[1] "GeeksforGeeks gives 100 percent success"

Using paste():

The paste() function allows you to concatenate multiple elements into a single string, with optional separators.

Example 3: Formatted string in R Programming using sprintf() Function

R




# Generate some example statistical results
mean_value <- 35.68
standard_deviation <- 7.42
 
# Create a formatted string to display the results
formatted_string <- sprintf("The mean is %.2f, and the standard deviation is %.2f",
                            mean_value, standard_deviation)
 
# Print the formatted string
cat(formatted_string)


Output:

The mean is 35.68, and the standard deviation is 7.42


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads