R sprintf() function - formatted output

R 语言实例R language examples

The R sprintf() function is used to format data as a string according to a specified format.

sprintf()'s format specifiers are consistent with C language style, allowing precise control over how numbers are displayed.

The syntax of the sprintf() function is as follows:

sprintf(fmt, ...)

Parameter description:

  • fmtFormat string, containing format placeholders such as %s, %d, %f.

  • ...Values to fill into the placeholders.

Format specifierDescriptionExample
%sStringsprintf("%s", "hello")
%dIntegersprintf("%d", 42)
%fFloating-point numbersprintf("%.2f", pi)
%eScientific notationsprintf("%e", 1000)

Example

# Format numbers
print(sprintf("pi is approximately %.2f", pi))
print(sprintf("Progress: %d%%", 85))

# Padding and alignment
print(sprintf("Number: %03d", c(1, 12, 123)))

# Multiple placeholders
print(sprintf("%s is %d years old, score %.1f",
              c("Zhang San", "Li Si"),
              c(25, 30),
              c(88.5, 92.3)))

Executing the above code produces the following output:

[1] "pi 约等于 3.14"
[1] "进度: 85%"
[1] "编号: 001" "编号: 012" "编号: 123"
[1] "张三 的年龄是 25 岁,成绩 88.5 分"
[2] "李四 的年龄是 30 岁,成绩 92.3 分"

R 语言实例R language examples

Other extensions