sprintf() Function in detail
The sprintf() function in R uses a format specified by the user to return the formatted string, inserting the values provided.
Syntax:
sprintf(format, values)
Parameters:
format: The format of the string for printing values.values: The variables or values to be inserted into the string.
Example 1: Formatted String using sprintf()
# R program to illustrate
# the use of sprintf() function
# Initializing values
name <- "Alice"
greeting <- "Good Morning"
# Calling sprintf() function
sprintf("%s, %s!", greeting, name)
Output:
[1] "Good Morning, Alice!"
In this example, sprintf() is used to create a formatted string where the placeholders %s are replaced by the values of the variables greeting and name.
Example 2: Formatted String with Numbers using sprintf()
# R program to illustrate
# the use of sprintf() function
# Initializing values
item <- "Apples"
quantity <- 12
price_per_item <- 2.5
# Calling sprintf() function
sprintf("The price for %d %s is $%.2f", quantity, item, quantity * price_per_item)
Output:
[1] "The price for 12 Apples is $30.00"
This example demonstrates using sprintf() to format a string that includes both text and numeric values, where the %d placeholder is used for integers, and %.2f is used for floating-point numbers.
Using paste(): The paste() function in R is used for concatenating elements into a single string, with optional separators between them.
Example 3: Formatted String using paste()
# Generate some example statistical results
mean_value <- 35.68
standard_deviation <- 7.42
# Create a formatted string to display the results
formatted_string <- paste("The mean is", round(mean_value, 2),
"and the standard deviation is", round(standard_deviation, 2))
# Print the formatted string
cat(formatted_string)
Output:
The mean is 35.68 and the standard deviation is 7.42
Here, paste() is used to concatenate the components of the string, and round() ensures the values are formatted to two decimal places.
Leave a Reply