R provides the sprintf() function that provides string formatting as the same C language. Specifically, the sprintf() method is a wrapper for the C library method of the same name.
sprintf in R
The sprintf() is a built-in R function that returns a character vector containing the formatted combination of text and variable values. It accepts format and input data as arguments and returns the character vector of length that of the input.
fmt: It is a character vector of format strings, each of up to 8192 bytes.
…: Those are the values to be passed into fmt. Only logical, integer, real, and character vectors are supported, but some coercion will be done.
The sprintf() method returns the character vector of length that of the longest input.
To format the decimal places in R, use the sprintf() function.
Let’s assign a floating-point number to the R variable.
data <- 19.211 sprintf("%f", data)
Here you can see that the default number of decimal places is printed six digits after the decimal point.
To control the decimal places in R, add the point and a number between the percentage sign and the f to the sprintf() function.
data <- 19.211 sprintf("%.8f", data)
As you can see that %.8f means 8 decimal places after the point. If you pass the %.10f, then it will go up to 10 decimal places after the point.
We can also round our numeric input value to only two digits after the decimal point.
data <- 19.211 sprintf("%.2f", data)
How to print Non-Numeric Values with sprintf() in R
To print the Non-Numeric Values in R, use the sprintf() method. You can also combine numeric values with non-numeric inputs.
data <- 19.211 sprintf("%+f", data)
Control Scientific Notation using sprintf() function
To control exponential notation in R, use the sprintf() function.
data <- 19.211 sprintf("%e", data)
You can return the upper case E to the RStudio console.
data <- 19.211 sprintf("%E", data)
Format Places Before Decimal Point
The sprintf() enables the formatting of the number of digits before the decimal separator. To print all digits before the decimal point, use the sprintf() function.
data <- 19.211 sprintf("%1.0f", data)
As you can see that you need to print a certain amount of leading blanks before our number without decimal places.
That is it for this tutorial.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.