Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R sprintf() Function - Formatted Output

R sprintf() Function - Formatted Output

R Language Examples R Language Examples

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:

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

print

(

sprintf

(

"pi is approximately %.2f"

,

pi

)

)

print

(

sprintf

(

"Progress: %d%%"

,

85

)

)

Padding and alignment

print

(

sprintf

(

"ID: %03d"

,

c

(

1

,

12

,

123

)

)

)

Multiple placeholders

print

(

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 R Language Examples