format_digits {mintyr} | R Documentation |
Format Numeric Columns with Specified Digits
Description
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.
Usage
format_digits(data, cols = NULL, digits = 2, percentage = FALSE)
Arguments
data |
A |
cols |
An optional numeric or character vector specifying the columns to format. If |
digits |
A non-negative integer specifying the number of decimal places to use. Defaults to |
percentage |
A logical value indicating whether to format the numbers as percentages. If |
Details
The function performs the following steps:
Validates the input parameters, ensuring that
data
is adata.frame
ordata.table
,cols
(if provided) are valid column names or indices, anddigits
is a non-negative integer.Converts
data
to adata.table
if it is not already one.Creates a formatting function based on the
digits
andpercentage
parameters:If
percentage = FALSE
, numbers are rounded todigits
decimal places.If
percentage = TRUE
, numbers are multiplied by 100, rounded todigits
decimal places, and a percent sign (%
) is appended.
Applies the formatting function to the specified columns:
If
cols
isNULL
, the function formats all numeric columns indata
.If
cols
is specified, only those columns are formatted.
Returns a new
data.table
with the formatted columns.
Value
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.
Note
The input
data
must be adata.frame
ordata.table
.If
cols
is specified, it must be a vector of valid column names or indices present indata
.The
digits
parameter must be a single non-negative integer.The original
data
is not modified; a modified copy is returned.
Examples
# 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
)
# 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
)