In this tutorial you will learn about the R String Format and its application with practical example.
R String Format
Sometime we may want to convert a number or string into any specific format. In R, the format() function is used to format numbers and strings into specified format.
Syntax:-
1 |
format(str, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none")) |
Above is the general syntax of format() function, here –
str:- It is a vector input representing a string.
digits:- Number of digits to be displayed.
nsmall:- It represents the min. number of digits after the decimal point.
scientific:- It is set to TRUE to display scientific notation.
width:- It represents the min. width to be displayed, it allows padding blank space in the beginning.
justify:- It is used to set display of the string to left, right or center.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# Number of digits to be displayed. Last digit rounded off. result <- format(10.123456789, digits = 9) print(result) # Display numbers in scientific notation. result <- format(c(5, 12.12345), scientific = TRUE) print(result) # The minimum number of digits after decimal point. result <- format(10.37, nsmall = 5) print(result) # Format treats everything as a string. result <- format(5) print(result) # Numbers are padded with blank in the beginning for width. result <- format(11.7, width = 6) print(result) # Left justify strings. result <- format("W3Adda", width = 8, justify = "l") print(result) # Justfy string with center. result <- format("W3Adda", width = 8, justify = "c") print(result) |
Output:-