R sprintf() Function - Formatted Output
The R sprintf() function is used to format data into strings according to a specified format.
The format specifiers of sprintf() follow the C language style, allowing precise control over how numbers are displayed.
The syntax of the sprintf() function is as follows:
sprintf(fmt, ...)
Parameter Description:
-
fmt A format string containing placeholders such as %s, %d, %f.
-
... The values to fill into the placeholders.
| Format specifier | Description | Example |
|---|---|---|
| %s | String | sprintf("%s", "hello") |
| %d | Integers | sprintf("%d", 42) |
| %f | Float (floating point number) | sprintf("%.2f", pi) |
| %e | Scientific notation | sprintf("%e", 1000) |
Example
Formatting numbers
(
sprintf
(
"pi is approximately %.2f"
,
pi
)
)
(
sprintf
(
"Progress: %d%%"
,
85
)
)
Padding and alignment
(
sprintf
(
"ID: %03d"
,
c
(
1
,
12
,
123
)
)
)
Multiple placeholders
(
sprintf
(
"%s is %d years old and scores %.1f points"
,
c
(
"Zhang San"
,
"Li Si"
)
,
c
(
25
,
30
)
,
c
(
88.5
,
92.3
)
)
)
The output of the code above is:
[1] "pi 约等于 3.14"
[1] "进度: 85%"
[1] "编号: 001" "编号: 012" "编号: 123"
[1] "张三 的年龄是 25 岁,成绩 88.5 分"
[2] "李四 的年龄是 30 岁,成绩 92.3 分"
R Language Examples