Formatting with sprintf()
Part of the Logic & Flow section of Coddy's R journey. Lesson 2 of 64.
sprintf() builds a string from a template. Each % placeholder is replaced by the next argument: %s for text, %d for whole numbers and %f for decimals.
name <- "Ada"
age <- 36
print(sprintf("%s is %d years old", name, age))Output:
[1] "Ada is 36 years old"%d accepts only whole numbers: sprintf("%d", 2.5) stops with an error.
A precision between % and f sets the number of decimals, so %.2f rounds to two places:
total <- 3 * 4.5 * 1.2
print(sprintf("Total: %.2f", total))Output:
[1] "Total: 16.20"A width pads the value to that many characters: %5d pads on the left, %-6s pads on the right and %03d pads with zeros. %% prints a percent sign.
print(sprintf("[%5d]", 42))
print(sprintf("[%-6s]", "tea"))
print(sprintf("%03d", 7))
print(sprintf("%d%%", 85))Output:
[1] "[ 42]"
[1] "[tea ]"
[1] "007"
[1] "85%"sprintf() is vectorized: with vector arguments it returns one string per element. cat() with sep = "\n" prints each string on its own line.
items <- c("tea", "cake")
prices <- c(4, 12.5)
lines <- sprintf("%-5s %6.2f", items, prices)
cat(lines, sep = "\n")Output:
tea 4.00
cake 12.50Challenge
EasyComplete receipt_line(item, qty, price). Return the item, the quantity and the line total (qty * price) in the form tea x3 = 13.50: the item, a space, x followed by the quantity, then = and the total with exactly two decimals.
The supplied code reads the item, the quantity and the price (one per line) and prints the returned value.
Try it yourself
receipt_line <- function(item, qty, price) {
# Write your code here
""
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(receipt_line(input[1], as.integer(input[2]), as.numeric(input[3])), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler