The format_digits
function formats numeric columns in a data frame or data table by rounding numbers to a specified number of decimal places and converting them to character strings. It can optionally format the numbers as percentages.
format_digits(data, cols = NULL, digits = 2, percentage = FALSE)
A data.frame
or data.table
. The input data containing numeric columns to format.
An optional numeric or character vector specifying the columns to format. If NULL
(default), all numeric columns are formatted.
A non-negative integer specifying the number of decimal places to use. Defaults to 2
.
A logical value indicating whether to format the numbers as percentages. If TRUE
, the numbers are multiplied by 100 and a percent sign (%
) is appended. Defaults to FALSE
.
A data.table
with the specified numeric columns formatted as character strings with the specified number of decimal places. If percentage = TRUE
, the numbers are shown as percentages.
The function performs the following steps:
Validates the input parameters, ensuring that data
is a data.frame
or data.table
, cols
(if provided) are valid column names or indices, and digits
is a non-negative integer.
Converts data
to a data.table
if it is not already one.
Creates a formatting function based on the digits
and percentage
parameters:
If percentage = FALSE
, numbers are rounded to digits
decimal places.
If percentage = TRUE
, numbers are multiplied by 100, rounded to digits
decimal places, and a percent sign (%
) is appended.
Applies the formatting function to the specified columns:
If cols
is NULL
, the function formats all numeric columns in data
.
If cols
is specified, only those columns are formatted.
Returns a new data.table
with the formatted columns.
The input data
must be a data.frame
or data.table
.
If cols
is specified, it must be a vector of valid column names or indices present in data
.
The digits
parameter must be a single non-negative integer.
The original data
is not modified; a modified copy is returned.
# Example: Number formatting demonstrations
# Setup test data
dt <- data.table::data.table(
a = c(0.1234, 0.5678), # Numeric column 1
b = c(0.2345, 0.6789), # Numeric column 2
c = c("text1", "text2") # Text column
)
# Example 1: Format all numeric columns
format_digits(
dt, # Input data table
digits = 2 # Round to 2 decimal places
)
#> a b c
#> <char> <char> <char>
#> 1: 0.12 0.23 text1
#> 2: 0.57 0.68 text2
# Example 2: Format specific column as percentage
format_digits(
dt, # Input data table
cols = c("a"), # Only format column 'a'
digits = 2, # Round to 2 decimal places
percentage = TRUE # Convert to percentage
)
#> a b c
#> <char> <num> <char>
#> 1: 12.34% 0.2345 text1
#> 2: 56.78% 0.6789 text2