View source: R/format_digits.R
format_digits | R Documentation |
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)
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 |
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.
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 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
)
# 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
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.