SoFunction
Updated on 2025-03-10

Explanation of R language format output sprintf example

Replace strings with %s

name <- 'max'
sprintf('my name is %s',name)
[1] "my name is max"

Replace integers with %d

age <- 18
sprintf('age:%d',age)
[1] "age:18"

Adding the number n before d can add n-a space instead of the number digit number digit number space

sprintf('age:%3d',age)
[1] "age: 18"

Add 0 before d and the number n can be added, and n can be added instead of 0 of the number digit number

sprintf('age:%07d',age)
[1] "age:0000018"

Replace floating point numbers with %f, %    m controls the output character width, n controls the decimal point

#Retain 5 decimal placessprintf('%.5f',pi)
[1] "3.14159"

Post %% represents percentage

sprintf("percent:99 %%")
[1] "percent:99 %"

This is the article about the explanation of R formatting and output sprintf examples. For more related R formatting and output sprintf content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!