R sprintf() function - formatted output
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 specifier | Description | Example |
|---|---|---|
| %s | String | sprintf("%s", "hello") |
| %d | Integer | sprintf("%d", 42) |
| %f | Floating-point number | sprintf("%.2f", pi) |
| %e | Scientific notation | sprintf("%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)))
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 分"Other extensions
R language examples