๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R String Formatting

A formatted string places values into set slots in a piece of text. sprintf builds such a string from one pattern and the values for its slots.

Text and number slots

The pattern holds one %s slot and two %d slots. The values fill the slots in order.

print(sprintf("%s scored %d of %d", "Ana", 9, 10))

Two digits after the point

The %.2f slot rounds the display to two digits. A whole half shows as 2.50 and keeps its trailing zero.

print(sprintf("Pi is about %.2f", 3.14159))
print(sprintf("%.2f", 2.5))

Padding with a zero

The %02d slot pads 7 to two digits. The second call builds a time with both parts padded.

print(sprintf("%02d", 7))
print(sprintf("%02d:%02d", 9, 5))

A report line from stored values

The values come from three stored names. sprintf places each value in its slot and builds one line.

name <- "Ana"
items <- 3
price <- 1.5
print(sprintf("%s bought %d pens at %.2f each", name, items, price))

Example

print(sprintf("%s scored %d of %d (%.1f%%)", "Ana", 9, 10, 90))

Key points

  • The first value in sprintf is the pattern text.
  • A %s slot in the pattern takes a text value.
  • A %d slot takes a whole number value.
  • The values after the pattern fill the slots in order.
  • A %.2f slot shows a number with two digits after the point.
  • The %.2f slot rounds the display and leaves the stored value alone.
  • A %02d slot pads a short number with a leading zero.
  • A %% pair in the pattern prints one percent sign.

In this example one sprintf call builds a full report line. The %% pair at the end prints a single percent sign after the score.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does print(sprintf("%02d", 7)) show?