You can use the sprintf() function in R to print formatted strings.
This function uses the following basic syntax:
sprintf(fmt, x)
where:
- fmt: The format to use
- x: The value to format
The following examples show how to use this function in practice.
Example 1: Format Digits After Decimal Point
The following code shows how to use sprintf() to only display two digits after a decimal point:
#define value x <- 15.49347782 #only display 2 digits after decimal place sprintf("%.2f", x) [1] "15.49"
Example 2: Format Digits Before Decimal Point
The following code shows how to use sprintf() to display ten digits before the decimal point:
#define value x <- 15435.4 #display 10 total digits before decimal place sprintf("%10.f", x) [1] " 15435"
Since there were only five digits before the decimal point to start with, the sprintf() function added another five blank spaces at the beginning of the string to make a total of 10 digits before the decimal point.
Example 3: Format Value Using Scientific Notation
The following code shows how to use sprintf() to display a value in scientific notation:
#define value x <- 15435.4 #display in scientific notation using lowercase e sprintf("%e", x) [1] "1.543540e+04" #display in scientific notation using uppercase E sprintf("%E", x) [1] "1.543540E+04"
Example 4: Format One Value in String
The following code shows how to use sprintf() to format a value in a string:
#define value x <- 5.4431 #display string with formatted value sprintf("I rode my bike about %.1f miles", x) [1] "I rode my bike about 5.4 miles"
Example 5: Format Multiple Values in String
The following code shows how to use sprintf() to format multiple values in a string:
#define values x1 <- 5.4431 x2 <- 10.778342 #display string with formatted values sprintf("I rode my bike %.1f miles and then ran %.2f miles", x1, x2) [1] "I rode my bike 5.4 miles and then ran 10.78 miles"
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use paste & paste0 Functions in R
How to Use the replace() Function in R
How to Use the View() Function in R