0
0
R Programmingprogramming~15 mins

String formatting with sprintf in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
String formatting with sprintf
📖 Scenario: You are preparing a report that shows the prices of fruits in a neat format. You want to display the fruit name and its price with exactly two decimal places.
🎯 Goal: Build a small R program that uses sprintf to format fruit prices as strings with two decimal places.
📋 What You'll Learn
Create a character vector called fruits with the values "Apple", "Banana", and "Cherry".
Create a numeric vector called prices with the values 1.2, 0.5, and 2.35.
Create a format string variable called format_str with the value "%s: $%.2f".
Use sprintf with format_str, fruits, and prices to create a character vector called formatted_prices.
Print the formatted_prices vector.
💡 Why This Matters
🌍 Real World
Formatting prices or other data neatly is common in reports, invoices, and user interfaces.
💼 Career
Knowing how to format strings precisely is useful for data presentation and creating readable outputs in data analysis and software development.
Progress0 / 4 steps
1
Create the fruit and price vectors
Create a character vector called fruits with the values "Apple", "Banana", and "Cherry". Also create a numeric vector called prices with the values 1.2, 0.5, and 2.35.
R Programming
Need a hint?

Use the c() function to create vectors in R.

2
Create the format string
Create a variable called format_str and set it to the string "%s: $%.2f" which will format a fruit name and its price with two decimal places.
R Programming
Need a hint?

The format string uses %s for strings and %.2f for floating numbers with 2 decimals.

3
Format the prices using sprintf
Use sprintf with format_str, fruits, and prices to create a character vector called formatted_prices.
R Programming
Need a hint?

Pass the format string first, then the vectors to sprintf.

4
Print the formatted prices
Print the formatted_prices vector to display the formatted fruit prices.
R Programming
Need a hint?

Use print(formatted_prices) to show the result.