Numbers and strings can be formatted as a specific style using the format () function.
Grammar
The basic syntax for the format () function is:
Format (x, digits, nsmall,scientific,width,justify = C ("Left", "right", "centre", "none"))
The following is a description of the parameters used:
- X-for vector input
- Digits-is the total number of digits displayed
- Nsmall-is the smallest digit to the right of the decimal point
- Scientific-set to true to display scientific notation
- Width-Indicates the minimum width to be displayed at the beginning by filling in whitespace
- Justify-is the string displayed on the left, right or center
Example
# total number of digits displayed. Last digit rounded off.result <-format (23.123456789, digits = 9) print (result) # Display numbers in scientific notation. Result <-Format (c (6, 13.14521), scientific = TRUE) print (Result) # The minimum number of digits to the right of the Deci Mal point.result <-Format (23.47, Nsmall = 5) print (result) # format treats everything as a string.result <-format (6) Print (Result) # Numbers is padded with blank in the beginning for Width.result <-format (13.7, width = 6) print (Result) # Left justify Strings.result <-format ("Hello", Width = 8, justify = "L") print (Result) # Justfy string with Center.result <-format ("Hello", Width = 8, justify = "C") print (Result)
When the above code executes, it produces the following result:
[1] "23.1234568" [1] "6.000000e+00" "1.314521e+01" [1] "23.47000" [1] "6" [1] " 13.7" [1] "Hello " [1] "Hello "
R language formatting numbers and string format functions