sprintf in R: How to Print Formatted String in R

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.

Syntax

sprintf(fmt, …)

Parameters

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.

Return Value

The sprintf() method returns the character vector of length that of the longest input.

Example

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)

Output

[1] "19.211100"

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)

Output

[1] "19.21100000"

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)

Output

[1] "19.21"

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)

Output

[1] "+19.211000"

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)

Output

[1] "1.921100E+01"

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)

Output

[1] "19"

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.

Leave a Comment