![]() |
VOOZH | about |
In R programming, the format() function formats numbers, strings and dates to meet presentation needs. It gives formatting features to modify the display of numeric values, strings and date/time information. This function is applied to regulate the number of decimal places, alignment, scientific notation, etc. The format() function makes data display in the required format, making it easier to read and appropriate for reporting or data analysis.
format(x, digits, nsmall, scientific, width, justify = c("left", "right", "center", "none"))
Parameters:
The format() function can also center strings according to the width and alignment given.
Example: Aligning Strings
[1] "GFG " [1] " GFG " [1] " GFG"
The format() method can also be applied to control the display of numbers, such as specifying decimal places, scientific notation and rounding numbers.
[1] "12.35" [1] "12.3457" [1] "12.34568" [1] "12.3456789"
[1] "1234" [1] "12.34568" [1] "1.234568e+01" [1] "12.34568"
When working with categorical data coded as numeric values (e.g., 1, 2, 3, 4), the format() function is not suitable for assigning meaningful labels. Instead, we should use factors to map values to descriptive categories.
Output:
age_group
Age 0-17 2
Age 18-44 2
Age 45-64 2
Age 65 or older 1
The format() function can also be utilized to format date-time objects in R. You can convert Date or POSIX objects to tailored string representations.
[1] "2025-04-23 09:16:49"
[1] "June 27, 2023"
Date-Time Format Codes: