0Pricing
R Academy · Lesson

Formatted Output with sprintf()

Control decimal places, padding, and alignment with sprintf format strings.

sprintf() Basics

sprintf() formats strings using a format string with placeholders. It works exactly like C's printf. The first argument is the format template; subsequent arguments fill the placeholders in order.

sprintf('There are %d items', 5)
sprintf('Hello, %s!', 'Alice')
sprintf('Price: %.2f', 9.999)

Integer and String Placeholders

%d formats an integer, %s formats a string, and %f formats a floating-point number. Each placeholder is replaced in order by the corresponding argument.

name <- 'Bob'
age  <- 34
score <- 88.5
sprintf('%s is %d years old with score %.1f', name, age, score)

All lessons in this course

  1. Building Strings with paste() and paste0()
  2. Formatted Output with sprintf()
  3. Displaying Output with cat() and print()
  4. String Padding and Alignment
← Back to R Academy