From 49df7fb0d1a4a812ed81c9b5189d95f735d048d2 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Mon, 8 Apr 2019 01:45:24 -0400 Subject: [PATCH 1/8] Include option to hide all column labels (#237) * Add the `column_labels.hidden` argument * Add option to return an empty string * Modify function call * Add line item to `gt_options_default()` tbl * Update help file using roxygen * Add tests for `column_labels.hidden = TRUE` --- R/gt_options_default.R | 1 + R/render_as_html.R | 2 +- R/tab_options.R | 9 +++++++++ R/utils_render_html.R | 13 ++++++++++++- man/tab_options.Rd | 9 ++++++--- tests/testthat/test-cols_label.R | 26 ++++++++++++++++++++++++++ 6 files changed, 55 insertions(+), 5 deletions(-) diff --git a/R/gt_options_default.R b/R/gt_options_default.R index c783c61039..555211ea70 100644 --- a/R/gt_options_default.R +++ b/R/gt_options_default.R @@ -17,6 +17,7 @@ gt_options_default <- function() { "column_labels_background_color", TRUE, "columns", NA_character_, "column_labels_font_size", TRUE, "columns", "16px", "column_labels_font_weight", TRUE, "columns", "initial", + "column_labels_hidden", FALSE, "columns", "FALSE", "row_group_background_color", TRUE, "row_group", NA_character_, "row_group_font_size", TRUE, "row_group", "16px", "row_group_font_weight", TRUE, "row_group", "initial", diff --git a/R/render_as_html.R b/R/render_as_html.R index 0628d742b8..60c2f2233a 100644 --- a/R/render_as_html.R +++ b/R/render_as_html.R @@ -63,7 +63,7 @@ render_as_html <- function(data) { columns_component <- create_columns_component_h( boxh_df, output_df, stub_available, spanners_present, - styles_resolved, stubhead_label, col_alignment) + styles_resolved, stubhead_label, col_alignment, opts_df) # Create the body component of the table body_component <- diff --git a/R/tab_options.R b/R/tab_options.R index dc67e60985..5dd2cc0c73 100644 --- a/R/tab_options.R +++ b/R/tab_options.R @@ -58,6 +58,7 @@ #' when striping rows. #' @param row.striping.include_table_body an option for whether to include the #' table body when striping rows. +#' @param column_labels.hidden an option to hide the column labels. #' @return an object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table with @@ -169,6 +170,7 @@ tab_options <- function(data, column_labels.background.color = NULL, column_labels.font.size = NULL, column_labels.font.weight = NULL, + column_labels.hidden = NULL, row_group.background.color = NULL, row_group.font.size = NULL, row_group.font.weight = NULL, @@ -329,6 +331,13 @@ tab_options <- function(data, opts_df <- opts_df_set(opts_df, "column_labels_font_weight", column_labels.font.weight) } + # column_labels.hidden + if (!is.null(column_labels.hidden)) { + + opts_df <- opts_df_set( + opts_df, "column_labels_hidden", column_labels.hidden) + } + # row_group.background.color if (!is.null(row_group.background.color)) { diff --git a/R/utils_render_html.R b/R/utils_render_html.R index 501a8f8f44..da9453fa07 100644 --- a/R/utils_render_html.R +++ b/R/utils_render_html.R @@ -394,7 +394,18 @@ create_columns_component_h <- function(boxh_df, spanners_present, styles_resolved, stubhead_label, - col_alignment) { + col_alignment, + opts_df) { + + # Should the column labels be hidden? + column_labels_hidden <- + opts_df %>% + opts_df_get(option = "column_labels_hidden") %>% + as.logical() + + if (column_labels_hidden) { + return("") + } # Get the style attrs for the spanner column headings spanner_style_attrs <- diff --git a/man/tab_options.Rd b/man/tab_options.Rd index b365383946..478e48f6ac 100644 --- a/man/tab_options.Rd +++ b/man/tab_options.Rd @@ -14,9 +14,10 @@ tab_options(data, table.width = NULL, table.font.size = NULL, heading.border.bottom.color = NULL, column_labels.background.color = NULL, column_labels.font.size = NULL, column_labels.font.weight = NULL, - row_group.background.color = NULL, row_group.font.size = NULL, - row_group.font.weight = NULL, row_group.border.top.style = NULL, - row_group.border.top.width = NULL, row_group.border.top.color = NULL, + column_labels.hidden = NULL, row_group.background.color = NULL, + row_group.font.size = NULL, row_group.font.weight = NULL, + row_group.border.top.style = NULL, row_group.border.top.width = NULL, + row_group.border.top.color = NULL, row_group.border.bottom.style = NULL, row_group.border.bottom.width = NULL, row_group.border.bottom.color = NULL, @@ -66,6 +67,8 @@ color code should be provided.} \item{column_labels.font.weight, row_group.font.weight}{the font weight of the \code{columns} and \code{row_group} text element.} +\item{column_labels.hidden}{an option to hide the column labels.} + \item{row_group.border.top.style, row_group.border.top.width, row_group.border.top.color}{the style, width, and color of the row group's top border.} \item{row_group.border.bottom.style, row_group.border.bottom.width, row_group.border.bottom.color}{the style, width, and color of the row group's bottom border.} diff --git a/tests/testthat/test-cols_label.R b/tests/testthat/test-cols_label.R index cccd99b01b..c402c67ecb 100644 --- a/tests/testthat/test-cols_label.R +++ b/tests/testthat/test-cols_label.R @@ -117,3 +117,29 @@ test_that("the function `cols_label()` works correctly", { gt(tbl) %>% cols_label(col_a = "col_1")) }) + +test_that("all column labels can be entirely hidden from view", { + + # Expect that the option `column_labels.hidden = TRUE` will + # remove the expected node with the classes of `gt_col_heading` + # and `gt_right` (i.e., the column labels) + expect_length( + tbl %>% + gt() %>% + tab_options(column_labels.hidden = TRUE) %>% + render_as_html() %>% + xml2::read_html() %>% + selection_text("[class='gt_col_heading gt_right']"), + 0) + + # Expect that not hiding the column labels yields a length + # four vector when using the same search + expect_length( + tbl %>% + gt() %>% + render_as_html() %>% + xml2::read_html() %>% + selection_text("[class='gt_col_heading gt_right']"), + 4) +}) + From 1f8f97b66b6715a49839af7683ae151c75b4067f Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Wed, 17 Apr 2019 22:53:49 -0400 Subject: [PATCH 2/8] Make several refactoring improvements to some `format_*()` functions (#244) * Add comment with a TODO * Refactor stmt in `fmt_percent()` * Remove unneeded stmt * Use different function call * Remove unneeded util function * Remove unneeded components in `switch()` * Remove unneeded util function * Remove extra space * Update several testthat tests * Make handling of parentheses consistent * Rename `paste_currency_str()` to be general * Use the `paste_symbol_str()` util fcn * Create a common `symbol_str` variable * Modify several testthat tests * Add the `perform_negative_formatting()` fcn * Simplify negative value formatting * Modify the `to_latex_math_mode()` fcn * Modify calls to `to_latex_math_mode()` * Incorporate `minus_mark` in `paste_symbol_str()` * Add a function factory for some `format_*()` fcns * Define the formatter `type` for some `format_*()` fcns * Remove `negative_val` arg in some `format_*()` fcns * Use the `num_formatter_factory()` fcn factory * Update help files using roxygen * Remove several unneeded testthat tests * Modify argument name * Update repeated function calls * Modify function name * Modify comment * Modify conditional statement * Update argument in function signature * Modify variable assignment * Modify function called * Update help file using roxygen * Update several testthat tests * Remove `x` from fcn signature * Modify roxygen documentation * Set default values * Reverse order of args in fcn signature * Update help file using roxygen * Add argument to fcn signature * Remove unneeded util function * Return early in certain circumstances * Reverse order of args in fcn signature * Use `x` in fcn body instead of `x_str_vals` * Add the `prettify_scientific_notation()` util fcn * Add a `force()` call for each arg * Refactor the `num_formatter_factory()` fcn * Avoid assigning the `type` variable * Call the `normalize_suffixing_inputs()` fcn * Modify all `num_formatter_factory()` calls * Modify two testthat tests * Modify roxygen documentation * Update help files using roxygen * Remove default `NULL` values in fcn signature * Apply series of transformations with `%>%` * Assign logical vector `x_vals_lt0` for reuse * Force all arguments using a list * Move references of `currency` to `symbol` * Use `symbol` in place of `currency` * Add roxygen documentation and comments * Modify roxygen documentation * Update help files using roxygen * Validate a non-NULL locale right away * Modify function name * Simplify signature of `num_fmt_factory()` * Extract variables from `var_list` * Add the `create_var_list()` util fcn * Remove unneeded code * Simplify transformations in function factory * Modify function signatures * Generate `sep|dec_mark` within function factory * Refactor several `fmt_*()` functions * Modify function signature * Use `num_fmt_factory_multi()` throughout * Add roxygen documentation * Remove the `contexts` arg * Refactor `fmt_*()` fcns * Refactor `fmt_*()` fcns * Tidy code and add roxygen documentation * Additional refactoring for `format_*()` functions (#260) * Get `minus_mark` just before usage * Get `parens_marks` just before usage * Get `symbol_str` just before usage --- R/format_data.R | 622 +++++++++++---------------- R/utils.R | 8 +- R/utils_formatters.R | 449 ++++++++++++++----- R/utils_general_str_formatting.R | 3 + man/data_color.Rd | 2 +- man/fmt.Rd | 10 +- man/fmt_currency.Rd | 47 +- man/fmt_date.Rd | 10 +- man/fmt_datetime.Rd | 12 +- man/fmt_markdown.Rd | 8 +- man/fmt_missing.Rd | 10 +- man/fmt_number.Rd | 44 +- man/fmt_passthrough.Rd | 12 +- man/fmt_percent.Rd | 39 +- man/fmt_scientific.Rd | 28 +- man/fmt_time.Rd | 11 +- man/tab_footnote.Rd | 2 +- man/tab_header.Rd | 2 +- man/tab_options.Rd | 2 +- man/tab_row_group.Rd | 2 +- man/tab_source_note.Rd | 2 +- man/tab_spanner.Rd | 2 +- man/tab_stubhead_label.Rd | 2 +- man/tab_style.Rd | 2 +- tests/testthat/test-fmt_currency.R | 6 +- tests/testthat/test-fmt_number.R | 9 - tests/testthat/test-fmt_percent.R | 14 +- tests/testthat/test-l_fmt_currency.R | 8 +- tests/testthat/test-l_fmt_number.R | 11 - tests/testthat/test-l_fmt_percent.R | 13 +- 30 files changed, 733 insertions(+), 659 deletions(-) diff --git a/R/format_data.R b/R/format_data.R index 1d6b566b36..9ff58d01ed 100644 --- a/R/format_data.R +++ b/R/format_data.R @@ -7,8 +7,6 @@ #' \itemize{ #' \item decimals: choice of the number of decimal places, option to drop #' trailing zeros, and a choice of the decimal symbol -#' \item negative values: choice of a negative sign or parentheses for values -#' less than zero #' \item digit grouping separators: options to enable/disable digit separators #' and provide a choice of separator symbol #' \item scaling: we can choose to scale targeted values by a multiplier value @@ -27,15 +25,15 @@ #' expression to the \code{rows} argument. See the Arguments section for more #' information on this. #' -#' @param data a table object that is created using the \code{\link{gt}()} +#' @param data A table object that is created using the \code{\link{gt}()} #' function. -#' @param columns the columns to format. Can either be a series of column names +#' @param columns The columns to format. Can either be a series of column names #' provided in \code{vars()}, a vector of column indices, or a helper function #' focused on selections. The select helper functions are: #' \code{\link{starts_with}()}, \code{\link{ends_with}()}, #' \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, #' and \code{\link{everything}()}. -#' @param rows optional rows to format. Not providing any value results in all +#' @param rows Optional rows to format. Not providing any value results in all #' rows in \code{columns} being formatted. Can either be a vector of row #' captions provided \code{c()}, a vector of row indices, or a helper function #' focused on selections. The select helper functions are: @@ -43,18 +41,18 @@ #' \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, #' and \code{\link{everything}()}. We can also use expressions to filter down #' to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}). -#' @param decimals an option to specify the exact number of decimal places to +#' @param decimals An option to specify the exact number of decimal places to #' use. The default number of decimal places is \code{2}. -#' @param drop_trailing_zeros a logical value that allows for removal of +#' @param drop_trailing_zeros A logical value that allows for removal of #' trailing zeros (those redundant zeros after the decimal mark). -#' @param negative_val the formatting to use for negative values. With -#' \code{signed} (the default), negative values will be shown with a negative -#' sign. Using \code{parens} will show the negative value in parentheses. -#' @param use_seps an option to use digit group separators. The type of digit +#' @param use_seps An option to use digit group separators. The type of digit #' group separator is set by \code{sep_mark} and overridden if a locale ID is #' provided to \code{locale}. This setting is \code{TRUE} by default. -#' @param scale_by a value to scale the input. The default is \code{1.0}. -#' @param suffixing an option to scale and apply suffixes to larger numbers +#' @param scale_by A value to scale the input. The default is \code{1.0}. All +#' numeric values will be multiplied by this value first before undergoing +#' formatting. This value will be ignored if using any of the \code{suffixing} +#' options (i.e., where \code{suffixing} is not set to \code{FALSE}). +#' @param suffixing An option to scale and apply suffixes to larger numbers #' (e.g., \code{1924000} can be transformed to \code{1.92M}). This option can #' accept a logical value, where \code{FALSE} (the default) will not perform #' this transformation and \code{TRUE} will apply thousands (\code{K}), @@ -69,21 +67,22 @@ #' numbers in the range of millions and billions will be in terms of #' millions). Any use of \code{suffixing} (where not \code{FALSE}) means that #' any value provided to \code{scale_by} will be ignored. -#' @param pattern a formatting pattern that allows for decoration of the +#' @param pattern A formatting pattern that allows for decoration of the #' formatted value. The value itself is represented by \code{{x}} and all #' other characters are taken to be string literals. -#' @param sep_mark the mark to use as a separator between groups of digits +#' @param sep_mark The mark to use as a separator between groups of digits #' (e.g., using \code{sep_mark = ","} with \code{1000} would result in a #' formatted value of \code{1,000}). -#' @param dec_mark the character to use as a decimal mark (e.g., using +#' @param dec_mark The character to use as a decimal mark (e.g., using #' \code{dec_mark = ","} with \code{0.152} would result in a formatted value #' of \code{0,152}). -#' @param locale an optional locale ID that can be used for formatting the value +#' @param locale An optional locale ID that can be used for formatting the value #' according the locale's rules. Examples include \code{"en_US"} for English #' (United States) and \code{"fr_FR"} for French (France). The use of a valid #' locale ID will override any values provided in \code{sep_mark} and -#' \code{dec_mark}. -#' @return an object of class \code{gt_tbl}. +#' \code{dec_mark}. We can use the \code{\link{info_locales}()} function as a +#' useful reference for all of the locales that are supported. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # format the `num` column as numeric @@ -132,7 +131,6 @@ fmt_number <- function(data, rows = NULL, decimals = 2, drop_trailing_zeros = FALSE, - negative_val = "signed", use_seps = TRUE, scale_by = 1.0, suffixing = FALSE, @@ -145,83 +143,13 @@ fmt_number <- function(data, sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps) dec_mark <- get_locale_dec_mark(locale, dec_mark) + # Stop function if `locale` does not have a valid value + validate_locale(locale) + # Normalize the `suffixing` input to either return a character vector # of suffix labels, or NULL (the case where `suffixing` is FALSE) suffix_labels <- normalize_suffixing_inputs(suffixing, scale_by) - # Create a function factory for the `fmt_number()` function - fmt_number_factory <- function(context = "html") { - - function(x) { - - # Define the marks by context - minus_mark <- context_minus_mark(context) - parens_marks <- context_parens_marks_number(context) - - # Determine which of `x` are not NA - non_na_x <- !is.na(x) - - # Create a possibly shorter vector of non-NA `x` values - x_vals <- x[non_na_x] - - # Create a tibble with scaled values for `x[non_na_x]` - # and the suffix labels to use for character formatting - suffix_df <- - num_suffix( - round(x_vals, decimals), - suffixes = suffix_labels, - scale_by = scale_by - ) - - # Scale the `x_vals` by the `scale_by` value - x_vals <- scale_x_values(x_vals, scale_by = suffix_df$scale_by) - - # Format all non-NA x values - x_str_vals <- - format_num_to_str( - x_vals, decimals, sep_mark, dec_mark, drop_trailing_zeros - ) - - # Paste vector of suffixes to the right of the `x_str_vals` - x_str_vals <- paste_right(x_str_vals, suffix_df$suffix) - - # Perform negative value formatting - if (any(x_vals < 0)) { - - # Handle replacement of the minus mark - x_str_vals <- - x_str_vals %>% - tidy_gsub("-", minus_mark, fixed = TRUE) - - # Handle case where negative values are to be placed within parentheses - if (negative_val == "parens") { - - # Selectively remove minus sign and paste between parentheses - x_str_vals[x_vals < 0] <- - paste_between( - x = gsub(paste0("^", minus_mark), "", x_str_vals[x_vals < 0]), - x_2 = parens_marks - ) - } - } - - # If in a LaTeX context, remove any double negative - # signs in the exponent - if (context == "latex") { - x_str_vals <- to_latex_math_mode(x_str_vals) - } - - # Handle formatting of pattern - x_str_vals <- apply_pattern_fmt_x(pattern, x_str_vals) - - # Create `x_str` with the same length as `x`; place the - # `x_str_vals` into `str` (at the non-NA indices) - x_str <- rep(NA_character_, length(x)) - x_str[non_na_x] <- x_str_vals - x_str - } - } - # Capture expression in `rows` and `columns` rows <- rlang::enquo(rows) columns <- rlang::enquo(columns) @@ -232,10 +160,27 @@ fmt_number <- function(data, data = data, columns = !!columns, rows = !!rows, - fns = list( - html = fmt_number_factory(context = "html"), - latex = fmt_number_factory(context = "latex"), - default = fmt_number_factory(context = "default") + fns = num_fmt_factory_multi( + pattern = pattern, + format_fn = function(x, context) { + + x_str <- character(length(x)) + + # Create the `suffix_df` object + suffix_df <- create_suffix_df(x, decimals, suffix_labels, scale_by) + + x %>% + # Scale the `x_vals` by the `scale_by` values + scale_x_values(suffix_df$scale_by) %>% + # Format numeric values to character-based numbers + format_num_to_str( + context = context, decimals = decimals, sep_mark = sep_mark, + dec_mark = dec_mark, drop_trailing_zeros = drop_trailing_zeros + ) %>% + # With large-number suffixing support, we paste the + # vector of suffixes to the right of the values + paste_right(suffix_df$suffix) + } ) ) } @@ -263,7 +208,7 @@ fmt_number <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # format the `num` column as partially @@ -302,82 +247,120 @@ fmt_scientific <- function(data, dec_mark = ".", locale = NULL) { + # Set default values + suffixing <- FALSE + use_seps <- TRUE + # Use locale-based marks if a locale ID is provided - sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps = TRUE) + sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps) dec_mark <- get_locale_dec_mark(locale, dec_mark) - # Create a function factory for the `fmt_scientific()` function - fmt_scientific_factory <- function(context = "html") { + # Stop function if `locale` does not have a valid value + validate_locale(locale) - function(x) { + # Normalize the `suffixing` input to either return a character vector + # of suffix labels, or NULL (the case where `suffixing` is FALSE) + suffix_labels <- normalize_suffixing_inputs(suffixing, scale_by) - # Define the marks by context - minus_mark <- context_minus_mark(context) - exp_marks <- context_exp_marks(context) + # Capture expression in `rows` and `columns` + rows <- rlang::enquo(rows) + columns <- rlang::enquo(columns) - # Determine which of `x` are not NA - non_na_x <- !is.na(x) + # Pass `data`, `columns`, `rows`, and the formatting + # functions as a function list to `fmt()` + fmt( + data = data, + columns = !!columns, + rows = !!rows, + fns = num_fmt_factory_multi( + pattern = pattern, + format_fn = function(x, context) { - # Create a possibly shorter vector of non-NA `x` values - x_vals <- x[non_na_x] + # Define the marks by context + exp_marks <- context_exp_marks(context) + minus_mark <- context_minus_mark(context) - # Scale the `x_vals` by the `scale_by` value - x_vals <- scale_x_values(x_vals, scale_by) + # Define the `replace_minus()` function + replace_minus <- function(x) { + x %>% tidy_gsub("-", minus_mark, fixed = TRUE) + } - # Determine which of `x` don't require the (x 10^n) - # since their order would be zero - small_pos <- has_order_zero(x_vals) + # Create the `suffix_df` object + suffix_df <- create_suffix_df(x, decimals, suffix_labels, scale_by) - # Format all non-NA x values - x_str_vals <- - format_num_to_str_e( - x_vals, decimals, sep_mark, dec_mark, - drop_trailing_zeros - ) + # Scale the `x_vals` by the `scale_by` values + x <- x %>% scale_x_values(suffix_df$scale_by) - # For any numbers that shouldn't have an exponent, remove - # that portion from the character version - if (any(small_pos)) { + x_str <- + x %>% + # Format numeric values to character-based numbers + format_num_to_str( + context = context, decimals = decimals, sep_mark = sep_mark, + dec_mark = dec_mark, drop_trailing_zeros = drop_trailing_zeros, + format = "e", replace_minus_mark = FALSE + ) - x_str_vals[small_pos] <- - split_scientific_notn(x_str_vals[small_pos])$num - } + # # Determine which values don't require the (x 10^n) + # # for scientific foramtting since their order would be zero + small_pos <- has_order_zero(x) - # For any non-NA numbers that do have an exponent, format - # those according to the output context - if (any(!small_pos)) { + # For any numbers that shouldn't have an exponent, remove + # that portion from the character version + x_str[small_pos] <- + split_scientific_notn(x_str[small_pos])$num %>% + replace_minus() - sci_parts <- split_scientific_notn(x_str_vals[!small_pos]) + # For any non-NA numbers that do have an exponent, format + # those according to the output context + sci_parts <- split_scientific_notn(x_str[!small_pos]) - x_str_vals[!small_pos] <- + x_str[!small_pos] <- paste0( - sci_parts$num, exp_marks[1], - sci_parts$exp, exp_marks[2] + sci_parts$num %>% replace_minus(), + exp_marks[1], + sci_parts$exp %>% replace_minus(), + exp_marks[2] ) + + x_str } + ) + ) +} - # Handle replacement of the minus mark in number - # and exponent parts - x_str_vals <- - x_str_vals %>% - tidy_gsub("-", minus_mark, fixed = TRUE) +#' Format values to take a predefined symbol +#' +#' @inheritParams fmt_number +#' @inheritParams fmt_currency +#' @return An object of class \code{gt_tbl}. +#' @noRd +fmt_symbol <- function(data, + columns, + rows = NULL, + symbol = "*", + accounting = FALSE, + decimals = NULL, + drop_trailing_zeros = FALSE, + use_seps = TRUE, + scale_by = 1.0, + suffixing = FALSE, + pattern = "{x}", + sep_mark = ",", + dec_mark = ".", + placement = "left", + incl_space = FALSE, + locale = NULL) { - # If in a LaTeX context, put formatted numbers - # in math mode - if (context == "latex") { - x_str_vals <- to_latex_math_mode(x_str_vals) - } + # Use locale-based marks if a locale ID is provided + sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps) + dec_mark <- get_locale_dec_mark(locale, dec_mark) - # Handle formatting of pattern - x_str_vals <- apply_pattern_fmt_x(pattern, x_str_vals) + # Stop function if `locale` does not have a valid value + validate_locale(locale) - # Create `x_str` with the same length as `x`; place the - # `x_str_vals` into `str` (at the non-NA indices) - x_str <- rep(NA_character_, length(x)) - x_str[non_na_x] <- x_str_vals - x_str - } - } + # Normalize the `suffixing` input to either return a character vector + # of suffix labels, or NULL (the case where `suffixing` is FALSE) + suffix_labels <- normalize_suffixing_inputs(suffixing, scale_by) # Capture expression in `rows` and `columns` rows <- rlang::enquo(rows) @@ -389,10 +372,64 @@ fmt_scientific <- function(data, data = data, columns = !!columns, rows = !!rows, - fns = list( - html = fmt_scientific_factory(context = "html"), - latex = fmt_scientific_factory(context = "latex"), - default = fmt_scientific_factory(context = "default") + fns = num_fmt_factory_multi( + pattern = pattern, + format_fn = function(x, context) { + + # Create the `x_str` vector + x_str <- character(length(x)) + + # Create the `suffix_df` object + suffix_df <- create_suffix_df(x, decimals, suffix_labels, scale_by) + + # Scale the `x_vals` by the `scale_by` value + x <- x %>% scale_x_values(suffix_df$scale_by) + + is_negative_x <- x < 0 + is_not_negative_x <- !is_negative_x + + if (any(is_not_negative_x)) { + + x_str[is_not_negative_x] <- + x[is_not_negative_x] %>% + # Format numeric values to character-based numbers + format_num_to_str_c( + context = context, decimals = decimals, sep_mark = sep_mark, + dec_mark = dec_mark, drop_trailing_zeros = drop_trailing_zeros + ) + } + + x_abs_str <- x_str + + if (any(is_negative_x)) { + + x_abs_str[is_negative_x] <- + x[is_negative_x] %>% + abs() %>% + # Format numeric values to character-based numbers + format_num_to_str_c( + context = context, decimals = decimals, sep_mark = sep_mark, + dec_mark = dec_mark, drop_trailing_zeros = drop_trailing_zeros + ) + } + + x_str <- + # Format values with a symbol string + format_symbol_str( + context = context, x_abs_str = x_abs_str, x = x, + symbol = symbol, incl_space = incl_space, + placement = placement + ) %>% + # Format values in accounting style + format_as_accounting( + x = x, context = context, accounting = accounting + ) %>% + # With large-number suffixing support, we paste the + # vector of suffixes to the right of the values + paste_right(suffix_df$suffix) + + x_str + } ) ) } @@ -410,8 +447,6 @@ fmt_scientific <- function(data, #' value. #' \item decimals: choice of the number of decimal places, option to drop #' trailing zeros, and a choice of the decimal symbol -#' \item negative values: choice of a negative sign or parentheses for values -#' less than zero #' \item digit grouping separators: options to enable/disable digit separators #' and provide a choice of separator symbol #' \item pattern: option to use a text pattern for decoration of the formatted @@ -428,9 +463,9 @@ fmt_scientific <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param incl_space an option on whether to include a space between the value +#' @param incl_space An option for whether to include a space between the value #' and the percent sign. The default is to not introduce a space character. -#' @param placement the placement of the percent sign. This can be either be +#' @param placement The placement of the percent sign. This can be either be #' \code{right} (the default) or \code{left}. #' @return an object of class \code{gt_tbl}. #' @examples @@ -459,7 +494,6 @@ fmt_percent <- function(data, rows = NULL, decimals = 2, drop_trailing_zeros = FALSE, - negative_val = "signed", use_seps = TRUE, pattern = "{x}", sep_mark = ",", @@ -468,103 +502,27 @@ fmt_percent <- function(data, placement = "right", locale = NULL) { - # Use locale-based marks if a locale ID is provided - sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps) - dec_mark <- get_locale_dec_mark(locale, dec_mark) - - # Create a function factory for the `fmt_percent()` function - fmt_percent_factory <- function(context = "html") { - - function(x) { - - # Define the marks by context - minus_mark <- context_minus_mark(context) - percent_mark <- context_percent_mark(context) - parens_marks <- context_parens_marks(context) - - # Determine which of `x` are not NA - non_na_x <- !is.na(x) - - # Create a possibly shorter vector of non-NA `x` values - x_vals <- x[non_na_x] - - # Scale the `x_vals` by the `scale_by` value - x_vals <- scale_x_values(x_vals, scale_by = 100) - - # Format all non-NA x values - x_str_vals <- - format_num_to_str( - x_vals, decimals, sep_mark, dec_mark, drop_trailing_zeros - ) - - # Handle placement of the percent symbol - x_str_vals <- - x_str_vals %>% - paste_on_side( - x_side = ifelse(incl_space, " ", ""), - direction = placement - ) %>% - paste_on_side( - x_side = percent_mark, - direction = placement - ) %>% - swap_adjacent_text_groups( - pattern_1 = percent_mark, - pattern_2 = "-" - ) - - # Perform negative value formatting - if (any(x_vals < 0)) { - - # Handle replacement of the minus mark - x_str_vals <- - x_str_vals %>% - tidy_gsub("-", minus_mark, fixed = TRUE) - - # Handle case where negative values are to be placed within parentheses - if (negative_val == "parens") { - - # Selectively remove minus sign and paste between parentheses - x_str_vals[x_vals < 0] <- - paste_between( - x = gsub(paste0("^", minus_mark), "", x_str_vals[x_vals < 0]), - x_2 = parens_marks - ) - } - } - - # If in a LaTeX context, remove any double negative - # signs in the exponent - if (context == "latex") { - x_str_vals <- to_latex_math_mode(x_str_vals) - } - - # Handle formatting of pattern - x_str_vals <- apply_pattern_fmt_x(pattern, x_str_vals) - - # Create `x_str` with the same length as `x`; place the - # `x_str_vals` into `str` (at the non-NA indices) - x_str <- rep(NA_character_, length(x)) - x_str[non_na_x] <- x_str_vals - x_str - } - } - # Capture expression in `rows` and `columns` rows <- rlang::enquo(rows) columns <- rlang::enquo(columns) - # Pass `data`, `columns`, `rows`, and the formatting - # functions as a function list to `fmt()` - fmt( + fmt_symbol( data = data, columns = !!columns, rows = !!rows, - fns = list( - html = fmt_percent_factory(context = "html"), - latex = fmt_percent_factory(context = "latex"), - default = fmt_percent_factory(context = "default") - ) + symbol = "%", + accounting = FALSE, + decimals = decimals, + drop_trailing_zeros = drop_trailing_zeros, + use_seps = use_seps, + scale_by = 100, + suffixing = FALSE, + pattern = pattern, + sep_mark = sep_mark, + dec_mark = dec_mark, + placement = placement, + incl_space = incl_space, + locale = locale ) } @@ -607,7 +565,7 @@ fmt_percent <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param currency the currency to use for the numeric value. This input can be +#' @param currency The currency to use for the numeric value. This input can be #' supplied as a 3-letter currency code (e.g., \code{"USD"} for U.S. Dollars, #' \code{"EUR"} for the Euro currency). Use \code{\link{info_currencies}()} to #' get an information table with all of the valid currency codes and examples @@ -617,13 +575,17 @@ fmt_percent <- function(data, #' "symbol"} option to view an information table with all of the supported #' currency symbol names along with examples. If nothing is provided then #' \code{"USD"} will be used. -#' @param use_subunits an option for whether the subunits portion of a currency +#' @param use_subunits An option for whether the subunits portion of a currency #' value should be displayed. -#' @param placement the placement of the currency symbol. This can be either be +#' @param accounting An option to use accounting style for currency values. With +#' \code{FALSE} (the default), negative values will be shown with a negative +#' sign. Using \code{accounting = TRUE} will put negative values in +#' parentheses. +#' @param placement The placement of the currency symbol. This can be either be #' \code{left} (the default) or \code{right}. -#' @param incl_space an option on whether to include a space between the value +#' @param incl_space An option for whether to include a space between the value #' and the currency symbol. The default is to not introduce a space character. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # format the `currency` column to have @@ -666,7 +628,7 @@ fmt_currency <- function(data, rows = NULL, currency = "USD", use_subunits = TRUE, - negative_val = "signed", + accounting = FALSE, decimals = NULL, use_seps = TRUE, scale_by = 1.0, @@ -678,118 +640,33 @@ fmt_currency <- function(data, incl_space = FALSE, locale = NULL) { - # Use locale-based marks if a locale ID is provided - sep_mark <- get_locale_sep_mark(locale, sep_mark, use_seps) - dec_mark <- get_locale_dec_mark(locale, dec_mark) + # Capture expression in `rows` and `columns` + rows <- rlang::enquo(rows) + columns <- rlang::enquo(columns) # Stop function if `currency` does not have a valid value - validate_currency(currency) + validate_currency(currency = currency) # Get the number of decimal places - decimals <- get_currency_decimals(currency, decimals, use_subunits) - - # Normalize the `suffixing` input to either return a character vector - # of suffix labels, or NULL (the case where `suffixing` is FALSE) - suffix_labels <- normalize_suffixing_inputs(suffixing, scale_by) - - # Create a function factory for the `fmt_currency()` function - fmt_currency_factory <- function(context = "html") { - - function(x) { - - # Define the marks by context - negative_currency_mark <- context_negative_currency_mark(context) - currency_str <- context_currency_str(context, currency) - currency_str_regex <- context_currency_str_regex(context) - parens_marks <- context_parens_marks(context) - - # Determine which of `x` are not NA - non_na_x <- !is.na(x) - - # Create a possibly shorter vector of non-NA `x` values - x_vals <- x[non_na_x] - - # Create a tibble with scaled values for `x[non_na_x]` - # and the suffix labels to use for character formatting - suffix_df <- - num_suffix( - round(x_vals, decimals), - suffixes = suffix_labels, - scale_by = scale_by - ) - - # Scale the `x_vals` by the `scale_by` value - x_vals <- scale_x_values(x_vals, scale_by = suffix_df$scale_by) - - # Format all non-NA x values - x_str_vals <- format_num_to_str_c(x_vals, decimals, sep_mark, dec_mark) - - # Paste vector of suffixes to the right of the `x_str_vals` - x_str_vals <- paste_right(x_str_vals, suffix_df$suffix) - - # Handle placement of the currency symbol - x_str_vals <- - x_str_vals %>% - paste_currency_str(currency_str, incl_space, placement) - - # Perform negative value formatting - if (any(x_vals < 0)) { - - # Handle replacement of the minus mark - x_str_vals <- - x_str_vals %>% - tidy_gsub("-", negative_currency_mark, fixed = TRUE) - - # Handle case where negative values are to be placed within parentheses - if (negative_val == "parens") { - - # Selectively remove minus sign and paste between parentheses - x_str_vals[x_vals < 0] <- - paste_between( - x = x_str_vals[x_vals < 0] %>% - tidy_gsub( - negative_currency_mark, "", - fixed = TRUE - ), - x_2 = parens_marks - ) - } - } - - # If in a LaTeX context, wrap values in math mode - if (context == "latex") { - - x_str_vals <- - x_str_vals %>% - to_latex_math_mode() - } - - # Handle formatting of pattern - x_str_vals <- apply_pattern_fmt_x(pattern, x_str_vals) + decimals <- get_currency_decimals(currency = currency, decimals, use_subunits) - # Create `x_str` with the same length as `x`; place the - # `x_str_vals` into `str` (at the non-NA indices) - x_str <- rep(NA_character_, length(x)) - x_str[non_na_x] <- x_str_vals - x_str - } - } - - # Capture expression in `rows` and `columns` - rows <- rlang::enquo(rows) - columns <- rlang::enquo(columns) - - # Pass `data`, `columns`, `rows`, and the formatting - # functions as a function list to `fmt()` - fmt( + fmt_symbol( data = data, columns = !!columns, rows = !!rows, - fns = list( - html = fmt_currency_factory(context = "html"), - latex = fmt_currency_factory(context = "latex"), - default = fmt_currency_factory(context = "default") - ) + symbol = currency, + accounting = accounting, + decimals = decimals, + drop_trailing_zeros = FALSE, + use_seps = use_seps, + scale_by = scale_by, + suffixing = suffixing, + pattern = pattern, + sep_mark = sep_mark, + dec_mark = dec_mark, + placement = placement, + incl_space = incl_space, + locale = locale ) } @@ -833,11 +710,11 @@ fmt_currency <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param date_style the date style to use. Supply a number (from \code{1} to +#' @param date_style The date style to use. Supply a number (from \code{1} to #' \code{14}) that corresponds to the preferred date style. Use #' \code{\link{info_date_style}()} to see the different numbered and named date #' presets. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `date` and `time` columns; @@ -948,10 +825,11 @@ fmt_date <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param time_style the time style to use. Supply a number (from \code{1} to +#' @param time_style The time style to use. Supply a number (from \code{1} to #' \code{5}) that corresponds to the preferred time style. Use #' \code{\link{info_time_style}()} to see the different numbered and named time #' presets. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `date` and `time` columns; @@ -1082,7 +960,7 @@ fmt_time <- function(data, #' @inheritParams fmt_number #' @inheritParams fmt_date #' @inheritParams fmt_time -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `datetime` column; @@ -1155,7 +1033,7 @@ fmt_datetime <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Create a few Markdown-based #' # text snippets @@ -1257,13 +1135,13 @@ fmt_markdown <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param escape an option to escape text according to the final output format +#' @param escape An option to escape text according to the final output format #' of the table. For example, if a LaTeX table is to be generated then LaTeX #' escaping would be performed during rendering. By default this is set to #' \code{TRUE} and setting to \code{FALSE} is useful in the case where #' LaTeX-formatted text should be passed through to the output LaTeX table #' unchanged. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `char` column; @@ -1373,9 +1251,9 @@ fmt_passthrough <- function(data, #' information on this. #' #' @inheritParams fmt_number -#' @param missing_text the text to be used in place of \code{NA} values in the +#' @param missing_text The text to be used in place of \code{NA} values in the #' rendered table. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # NA values in different columns will @@ -1470,8 +1348,8 @@ fmt_missing <- function(data, #' \code{rows} argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @param fns a single formatting function or a named list of functions. -#' @return an object of class \code{gt_tbl}. +#' @param fns Either a single formatting function or a named list of functions. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `exibble` to create a gt table; #' # format the numeric values in the `num` diff --git a/R/utils.R b/R/utils.R index 5ac18e838e..07c31f5c27 100644 --- a/R/utils.R +++ b/R/utils.R @@ -372,13 +372,13 @@ markdown_to_text <- function(text) { #' final decoration of the formatted values. We use \pkg{glue}'s semantics here #' and reserve \code{x} to be the formatted values, and, we can use \code{x} #' multiple times in the pattern. -#' @param pattern A formatting pattern that allows for decoration of the -#' formatted value (defined here as \code{x}). #' @param values The values (as a character vector) that are formatted within #' the \code{fmt_*()} function. +#' @param pattern A formatting pattern that allows for decoration of the +#' formatted value (defined here as \code{x}). #' @noRd -apply_pattern_fmt_x <- function(pattern, - values) { +apply_pattern_fmt_x <- function(values, + pattern) { vapply( values, diff --git a/R/utils_formatters.R b/R/utils_formatters.R index 99c548b363..352ec85b03 100644 --- a/R/utils_formatters.R +++ b/R/utils_formatters.R @@ -2,11 +2,13 @@ #' #' @param table The table to filter down to one row. #' @param column The column from which the single value should be obtained. -#' @param ... The arguments passed to `dplyr::filter()` +#' @param ... The arguments passed to `dplyr::filter()`. #' @import rlang #' @importFrom dplyr filter #' @noRd -filter_table_to_value <- function(table, column, ...) { +filter_table_to_value <- function(table, + column, + ...) { filter_args_enquos <- rlang::enquos(...) column_enquo <- rlang::enquo(column) @@ -33,7 +35,7 @@ validate_locale <- function(locale) { # Stop function if the `locale` provided # isn't a valid one - if (!(locale %in% locales$base_locale_id)) { + if (!is.null(locale) && !(locale %in% locales$base_locale_id)) { stop("The supplied `locale` is not available in the list of supported locales.\n", " * Use the `info_locales()` function to see which locales can be used.", call. = FALSE) @@ -66,7 +68,6 @@ validate_currency <- function(currency) { #' functions. This is expected as `NULL` if not supplied by the user. #' @param default The default value for the `sep_mark`. #' @param use_seps A logical value for whether to use separators at all. -#' @importFrom dplyr filter pull #' @noRd get_locale_sep_mark <- function(locale = NULL, default, @@ -84,10 +85,6 @@ get_locale_sep_mark <- function(locale = NULL, return(default) } - # Stop function if the `locale` provided - # isn't a valid one - validate_locale(locale) - # Get the correct `group_sep` value from the # `gt:::locales` lookup table sep_mark <- @@ -106,7 +103,6 @@ get_locale_sep_mark <- function(locale = NULL, #' @param locale The user-supplied `locale` value, found in several `fmt_*()` #' functions. This is expected as `NULL` if not supplied by the user. #' @param default The default value for the `dec_mark`. -#' @importFrom dplyr filter pull #' @noRd get_locale_dec_mark <- function(locale = NULL, default) { @@ -117,10 +113,6 @@ get_locale_dec_mark <- function(locale = NULL, return(default) } - # Stop function if the `locale` provided - # isn't a valid one - validate_locale(locale) - # Get the correct `dec_sep` value from the # `gt:::locales` lookup table filter_table_to_value(locales, dec_sep, base_locale_id == locale) @@ -137,6 +129,12 @@ has_order_zero <- function(x) { ) & !is.na(x) } +#' Get the correct number of decimal places for a specified currency +#' +#' @param currency The currency to use for the numeric value. +#' @param decimals The request number of decimal places. +#' @param use_subunits An option for whether the subunits portion of a currency +#' value should be displayed. #' @noRd get_currency_decimals <- function(currency, decimals, @@ -191,47 +189,40 @@ scale_x_values <- function(x, #' A `formatC()` call for `fmt_number()` and `fmt_percent()` #' #' @param x A vector of numeric values. +#' @param context The output context. #' @param decimals The number of decimal places (`digits`). #' @param sep_mark The separator for number groups (`big.mark`). #' @param dec_mark The decimal separator mark (`decimal.mark`). -#' @param format The numeric format for `formatC()`. #' @param drop_trailing_zeros Option to exclude trailing decimal zeros. +#' @param format The numeric format for `formatC()`. +#' @param replace_minus_mark An option for whether the minus sign should be +#' replaced with the minus mark. #' @noRd format_num_to_str <- function(x, + context, decimals, sep_mark, dec_mark, drop_trailing_zeros, - format = "f") { - - formatC( - x = x, - digits = decimals, - mode = "double", - big.mark = sep_mark, - decimal.mark = dec_mark, - format = format, - drop0trailing = drop_trailing_zeros - ) -} - -#' A `formatC()` call for `fmt_scientific()` -#' -#' @inheritParams format_num_to_str -#' @noRd -format_num_to_str_e <- function(x, - decimals, - sep_mark, - dec_mark, - drop_trailing_zeros) { + format = "f", + replace_minus_mark = TRUE) { + + x_str <- + formatC( + x = x, + digits = decimals, + mode = "double", + big.mark = sep_mark, + decimal.mark = dec_mark, + format = format, + drop0trailing = drop_trailing_zeros + ) + + if (replace_minus_mark) { + x_str <- format_minus(x_str = x_str, x = x, context = context) + } - format_num_to_str( - x, - decimals, - sep_mark, - dec_mark, - format = "e", - drop_trailing_zeros) + x_str } #' A `formatC()` call for `fmt_currency()` @@ -239,28 +230,42 @@ format_num_to_str_e <- function(x, #' @inheritParams format_num_to_str #' @noRd format_num_to_str_c <- function(x, + context, decimals, sep_mark, - dec_mark) { + dec_mark, + drop_trailing_zeros = FALSE) { format_num_to_str( - x, - decimals, - sep_mark, - dec_mark, - format = "f", - drop_trailing_zeros = FALSE) + x = x, + context = context, + decimals = decimals, + sep_mark = sep_mark, + dec_mark = dec_mark, + drop_trailing_zeros = drop_trailing_zeros, + format = "f" + ) } #' Surround formatted values with `$`s for LaTeX #' +#' @param x Numeric values in `character` form. +#' @param context The output context. #' @noRd -to_latex_math_mode <- function (x) { +to_latex_math_mode <- function(x, + context) { - x %>% - paste_between(x_2 = c("$", "$")) + if (context != "latex") { + return(x) + } else { + return(x %>% paste_between(x_2 = c("$", "$"))) + } } +#' Obtain the contextually correct minus mark +#' +#' @param context The output context. +#' @noRd context_minus_mark <- function(context) { switch(context, @@ -268,29 +273,33 @@ context_minus_mark <- function(context) { "-") } -context_negative_currency_mark <- function(context) { +#' Obtain the contextually correct percent mark +#' +#' @param context The output context. +#' @noRd +context_percent_mark <- function(context) { switch(context, - html = "−", - "-") + html = "%", + latex = "\\%", + "%") } +#' Obtain the contextually correct pair of parentheses +#' +#' @param context The output context. +#' @noRd context_parens_marks <- function(context) { switch(context, - html = c("(", ")"), - latex = c("\\left(", "\\right)"), - c("(", ")")) -} - -context_parens_marks_number <- function(context) { - - switch(context, - html = c("(", ")"), latex = c("(", ")"), c("(", ")")) } +#' Obtain the contextually correct pair of opening/closing exponential strings +#' +#' @param context The output context. +#' @noRd context_exp_marks <- function(context) { switch(context, @@ -299,71 +308,293 @@ context_exp_marks <- function(context) { c(" x 10(", ")")) } -context_percent_mark <- function(context) { - switch(context, - html = "%", - latex = "\\%", - "%") -} - -context_currency_str_regex <- function(context) { +#' Obtain the contextually correct symbol string +#' +#' @param context The output context. +#' @param symbol A symbol, which could be empty (NULL), a percent sign (`%`), or +#' a currency symbol. +#' @noRd +context_symbol_str <- function(context, + symbol) { - switch(context, - latex = "\\\\$", - "\\$") -} + # If we supply `NULL` as `symbol`, then + # return an empty string + if (is.null(symbol)) { + return("") + } -context_currency_str <- function(context, currency) { + # If we supply a percent sign as `symbol`, + # get the contextually correct percent mark + if (symbol == "%") { + return(context_percent_mark(context)) + } + # Get the contextually correct currency string switch(context, html = { - get_currency_str(currency) + symbol %>% + get_currency_str() }, latex = { - currency %>% + symbol %>% get_currency_str(fallback_to_code = TRUE) %>% markdown_to_latex() %>% paste_between(x_2 = c("\\text{", "}")) }, { - currency %>% + symbol %>% get_currency_str(fallback_to_code = TRUE) }) } -paste_currency_str <- function(x, - currency_str, - incl_space, - placement) { - - vapply(FUN.VALUE = character(1), USE.NAMES = FALSE, x, function(x) { +#' Paste a symbol string to a formatted number +#' +#' @param x_abs_str Absolute numeric values in `character` form. +#' @param x Numeric values in `numeric` form. +#' @param context The output context. +#' @param symbol The symbol. +#' @param incl_space A logical value indicating whether a single space character +#' should separate the symbols and the formatted values. +#' @param placement Either `left` or `right` (this is the placement of the +#' symbol string relative to the formatted, numeric values). +#' @noRd +format_symbol_str <- function(x_abs_str, + x, + context, + symbol, + incl_space, + placement) { - if (grepl("^-", x)) { - x %>% - tidy_gsub("^-", "") %>% - paste_on_side( - x_side = ifelse(incl_space, " ", ""), - direction = placement - ) %>% - paste_on_side( - x_side = currency_str, - direction = placement - ) %>% - paste_left("-") + symbol_str <- context_symbol_str(context, symbol) - } else { + if (symbol_str == "") { + return(x_abs_str) + } - x %>% - paste_on_side( - x_side = ifelse(incl_space, " ", ""), - direction = placement - ) %>% - paste_on_side( - x_side = currency_str, - direction = placement - ) + vapply(FUN.VALUE = character(1), USE.NAMES = FALSE, seq_along(x), function(i) { + + # Using absolute value format, the minus mark will + # be added later + x_i <- x[i] + x_str_i <- x_abs_str[i] + + # Place possible space and symbol on correct side of value + x_str_i <- + x_str_i %>% + paste_on_side( + x_side = ifelse(incl_space, " ", ""), + direction = placement + ) %>% + paste_on_side( + x_side = symbol_str, + direction = placement + ) + + # Create the minus mark for the context + minus_mark <- context_minus_mark(context) + + # Place the `minus_mark` onto the formatted strings + if (x_i < 0) { + x_str_i <- + x_str_i %>% + paste_left(minus_mark) } + + x_str_i }) } + +#' Transform currency values to accounting style +#' +#' @param x_str Numeric values in `character` form. +#' @param x Numeric values in `numeric` form. +#' @param context The output context. +#' @noRd +format_minus <- function(x_str, + x, + context) { + + # Store logical vector of `x_vals` < 0 + x_lt0 <- x < 0 + + # Return values unchanged if there are no negative values + if (!any(x_lt0)) { + return(x_str) + } + + # Create the minus mark for the context + minus_mark <- context_minus_mark(context) + + # Handle replacement of the minus mark + x_str %>% tidy_gsub("-", minus_mark, fixed = TRUE) +} + +#' Transform currency values to accounting style +#' +#' @param x_str Numeric values in `character` form. +#' @param x Numeric values in `numeric` form. +#' @param context The output context. +#' @param accounting A logical value that indicates whether accounting style +#' should be used. +#' @noRd +format_as_accounting <- function(x_str, + x, + context, + accounting) { + + # TODO: Handle using `x_abs_str` instead + + # Store logical vector of `x` < 0 + x_lt0 <- x < 0 + + # Return values unchanged if there are no negative values + if (!any(x_lt0)) { + return(x_str) + } + + # Handle case where negative values are to be placed within parentheses + if (accounting) { + + # Create the minus and parens marks for the context + minus_mark <- context_minus_mark(context) + parens_marks <- context_parens_marks(context) + + # Selectively remove minus sign and paste between parentheses + x_str[x_lt0] <- + x_str[x_lt0] %>% + tidy_gsub(minus_mark, "", fixed = TRUE) %>% + paste_between(x_2 = parens_marks) + } + + x_str +} + +#' Provide a nicer format for numbers in scientific notation +#' +#' @param x Numeric values in `character` form. +#' @param context The output context. +#' @param small_pos A logical vector the length of `x` that indicates whether +#' values should be decorated. +#' @param exp_marks A character vector (length of two) that encloses the +#' exponential power value. +#' @noRd +prettify_scientific_notation <- function(x, + context, + small_pos, + exp_marks) { + + if (!any(grepl("e|E", x))) { + return(x) + } + + # For any numbers that shouldn't have an exponent, remove + # that portion from the character version + x[small_pos] <- + split_scientific_notn(x[small_pos])$num + + # For any non-NA numbers that do have an exponent, format + # those according to the output context + sci_parts <- split_scientific_notn(x[!small_pos]) + + x[!small_pos] <- + paste0( + sci_parts$num, exp_marks[1], + sci_parts$exp, exp_marks[2] + ) + + # Create the minus mark for the context + minus_mark <- context_minus_mark(context) + + # Handle replacement of the minus mark in number + # and exponent parts + x %>% + tidy_gsub("-", minus_mark, fixed = TRUE) +} + +#' Create the data frame with suffixes and scaling values +#' +#' @param x Numeric values in `numeric` form. +#' @param decimals The exact number of decimal places to be used in the +#' formatted numeric value. +#' @param suffix_labels The vector of suffix labels to use. +#' @param scale_by A value to scale the input. +#' @noRd +create_suffix_df <- function(x, + decimals, + suffix_labels, + scale_by) { + + # Create a tibble with scaled values for `x` and the + # suffix labels to use for character formatting + num_suffix( + round(x, decimals), + suffixes = suffix_labels, + scale_by = scale_by + ) +} + +#' Create a list of function calls for all numeric `fmt_*()` functions +#' +#' @param pattern The user-defined formatting pattern that allows for decoration +#' of the formatted value. +#' @param format_fn A function for formatting the numeric values. +#' @noRd +num_fmt_factory_multi <- function(pattern, + format_fn) { + + # Define the contexts + contexts <- c("html", "latex", "default") + + # Upgrade `contexts` to have names + names(contexts) <- contexts + + # Generate a named list of factory functions, with one + # component per context + lapply(contexts, function(x) { + num_fmt_factory(context = x, pattern = pattern, format_fn = format_fn) + }) +} + +#' A factory function used for all numeric `fmt_*()` functions +#' +#' @param context The output context. +#' @param pattern The user-defined formatting pattern that allows for decoration +#' of the formatted value. +#' @param format_fn A function for formatting the numeric values. +#' @noRd +num_fmt_factory <- function(context, + pattern, + format_fn) { + + # Force all arguments + force(context) + force(pattern) + force(format_fn) + + function(x) { + + # Determine which of `x` are not NA + non_na_x <- !is.na(x) + + # Create a possibly shorter vector of non-NA `x` values + x_vals <- x[non_na_x] + + # Apply a series of transformations to `x_str_vals` + x_str_vals <- + x_vals %>% + # Format all non-NA x values with a formatting function + format_fn(context) %>% + # If in a LaTeX context, wrap values in math mode + to_latex_math_mode(context) %>% + # Handle formatting of pattern + apply_pattern_fmt_x(pattern) + + # Create `x_str` with the same length as `x`; place the + # `x_str_vals` into `str` (at the non-NA indices) + x_str <- rep(NA_character_, length(x)) + x_str[non_na_x] <- x_str_vals + x_str + } +} diff --git a/R/utils_general_str_formatting.R b/R/utils_general_str_formatting.R index d35dfde4c8..404900324f 100644 --- a/R/utils_general_str_formatting.R +++ b/R/utils_general_str_formatting.R @@ -14,6 +14,9 @@ split_string_2 <- function(x, before = NULL, after = NULL) { + # TODO: use `split` instead of before/after and include + # a `dir` option (for "before" or "after" splitting) + # Stop function if `x` is not of class character if (!inherits(x, "character")) { stop("Internal error in `gt:::paste_within()`:\n", diff --git a/man/data_color.Rd b/man/data_color.Rd index 4afacd0416..69e8d5c709 100644 --- a/man/data_color.Rd +++ b/man/data_color.Rd @@ -8,7 +8,7 @@ data_color(data, columns, colors, alpha = NULL, apply_to = "bkgd", autocolor_text = TRUE) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{columns}{the columns wherein changes to cell data colors should occur.} diff --git a/man/fmt.Rd b/man/fmt.Rd index c168e3988c..7b3fc6fe21 100644 --- a/man/fmt.Rd +++ b/man/fmt.Rd @@ -7,17 +7,17 @@ fmt(data, columns = NULL, rows = NULL, fns) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -26,10 +26,10 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{fns}{a single formatting function or a named list of functions.} +\item{fns}{Either a single formatting function or a named list of functions.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The \code{fmt()} function provides greater control in formatting raw data diff --git a/man/fmt_currency.Rd b/man/fmt_currency.Rd index 024cc14fe0..e828856699 100644 --- a/man/fmt_currency.Rd +++ b/man/fmt_currency.Rd @@ -5,23 +5,23 @@ \title{Format values as currencies} \usage{ fmt_currency(data, columns, rows = NULL, currency = "USD", - use_subunits = TRUE, negative_val = "signed", decimals = NULL, + use_subunits = TRUE, accounting = FALSE, decimals = NULL, use_seps = TRUE, scale_by = 1, suffixing = FALSE, pattern = "{x}", sep_mark = ",", dec_mark = ".", placement = "left", incl_space = FALSE, locale = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -30,7 +30,7 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{currency}{the currency to use for the numeric value. This input can be +\item{currency}{The currency to use for the numeric value. This input can be supplied as a 3-letter currency code (e.g., \code{"USD"} for U.S. Dollars, \code{"EUR"} for the Euro currency). Use \code{\link{info_currencies}()} to get an information table with all of the valid currency codes and examples @@ -41,23 +41,27 @@ process. Use \code{\link{info_currencies}()} with the \code{type == currency symbol names along with examples. If nothing is provided then \code{"USD"} will be used.} -\item{use_subunits}{an option for whether the subunits portion of a currency +\item{use_subunits}{An option for whether the subunits portion of a currency value should be displayed.} -\item{negative_val}{the formatting to use for negative values. With -\code{signed} (the default), negative values will be shown with a negative -sign. Using \code{parens} will show the negative value in parentheses.} +\item{accounting}{An option to use accounting style for currency values. With +\code{FALSE} (the default), negative values will be shown with a negative +sign. Using \code{accounting = TRUE} will put negative values in +parentheses.} -\item{decimals}{an option to specify the exact number of decimal places to +\item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} -\item{use_seps}{an option to use digit group separators. The type of digit +\item{use_seps}{An option to use digit group separators. The type of digit group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} -\item{scale_by}{a value to scale the input. The default is \code{1.0}.} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All +numeric values will be multiplied by this value first before undergoing +formatting. This value will be ignored if using any of the \code{suffixing} +options (i.e., where \code{suffixing} is not set to \code{FALSE}).} -\item{suffixing}{an option to scale and apply suffixes to larger numbers +\item{suffixing}{An option to scale and apply suffixes to larger numbers (e.g., \code{1924000} can be transformed to \code{1.92M}). This option can accept a logical value, where \code{FALSE} (the default) will not perform this transformation and \code{TRUE} will apply thousands (\code{K}), @@ -73,32 +77,33 @@ numbers in the range of millions and billions will be in terms of millions). Any use of \code{suffixing} (where not \code{FALSE}) means that any value provided to \code{scale_by} will be ignored.} -\item{pattern}{a formatting pattern that allows for decoration of the +\item{pattern}{A formatting pattern that allows for decoration of the formatted value. The value itself is represented by \code{{x}} and all other characters are taken to be string literals.} -\item{sep_mark}{the mark to use as a separator between groups of digits +\item{sep_mark}{The mark to use as a separator between groups of digits (e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value of \code{1,000}).} -\item{dec_mark}{the character to use as a decimal mark (e.g., using +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} -\item{placement}{the placement of the currency symbol. This can be either be +\item{placement}{The placement of the currency symbol. This can be either be \code{left} (the default) or \code{right}.} -\item{incl_space}{an option on whether to include a space between the value +\item{incl_space}{An option for whether to include a space between the value and the currency symbol. The default is to not introduce a space character.} -\item{locale}{an optional locale ID that can be used for formatting the value +\item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}.} +\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a +useful reference for all of the locales that are supported.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ With numeric values in a \pkg{gt} table, we can perform currency-based diff --git a/man/fmt_date.Rd b/man/fmt_date.Rd index 23cadcce35..413237405a 100644 --- a/man/fmt_date.Rd +++ b/man/fmt_date.Rd @@ -7,17 +7,17 @@ fmt_date(data, columns, rows = NULL, date_style = 2) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -26,13 +26,13 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{date_style}{the date style to use. Supply a number (from \code{1} to +\item{date_style}{The date style to use. Supply a number (from \code{1} to \code{14}) that corresponds to the preferred date style. Use \code{\link{info_date_style}()} to see the different numbered and named date presets.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Format input date values that are either of the \code{Date} type, or, are diff --git a/man/fmt_datetime.Rd b/man/fmt_datetime.Rd index e8d6984224..b778472de9 100644 --- a/man/fmt_datetime.Rd +++ b/man/fmt_datetime.Rd @@ -8,17 +8,17 @@ fmt_datetime(data, columns, rows = NULL, date_style = 2, time_style = 2) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -27,18 +27,18 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{date_style}{the date style to use. Supply a number (from \code{1} to +\item{date_style}{The date style to use. Supply a number (from \code{1} to \code{14}) that corresponds to the preferred date style. Use \code{\link{info_date_style}()} to see the different numbered and named date presets.} -\item{time_style}{the time style to use. Supply a number (from \code{1} to +\item{time_style}{The time style to use. Supply a number (from \code{1} to \code{5}) that corresponds to the preferred time style. Use \code{\link{info_time_style}()} to see the different numbered and named time presets.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Format input date-time values that are character-based and expressed diff --git a/man/fmt_markdown.Rd b/man/fmt_markdown.Rd index aa2cbd6cb6..c5b6e6acbb 100644 --- a/man/fmt_markdown.Rd +++ b/man/fmt_markdown.Rd @@ -7,17 +7,17 @@ fmt_markdown(data, columns, rows = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -27,7 +27,7 @@ and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Any Markdown-formatted text in the incoming cells will be transformed to the diff --git a/man/fmt_missing.Rd b/man/fmt_missing.Rd index cc0a1e0281..ad231fcdd7 100644 --- a/man/fmt_missing.Rd +++ b/man/fmt_missing.Rd @@ -7,17 +7,17 @@ fmt_missing(data, columns, rows = NULL, missing_text = "---") } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -26,11 +26,11 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{missing_text}{the text to be used in place of \code{NA} values in the +\item{missing_text}{The text to be used in place of \code{NA} values in the rendered table.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Wherever there is missing data (i.e., \code{NA} values) a customizable mark diff --git a/man/fmt_number.Rd b/man/fmt_number.Rd index 8deed2e2ed..da2129b4fe 100644 --- a/man/fmt_number.Rd +++ b/man/fmt_number.Rd @@ -5,22 +5,22 @@ \title{Format numeric values} \usage{ fmt_number(data, columns, rows = NULL, decimals = 2, - drop_trailing_zeros = FALSE, negative_val = "signed", - use_seps = TRUE, scale_by = 1, suffixing = FALSE, - pattern = "{x}", sep_mark = ",", dec_mark = ".", locale = NULL) + drop_trailing_zeros = FALSE, use_seps = TRUE, scale_by = 1, + suffixing = FALSE, pattern = "{x}", sep_mark = ",", + dec_mark = ".", locale = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -29,23 +29,22 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{decimals}{an option to specify the exact number of decimal places to +\item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} -\item{drop_trailing_zeros}{a logical value that allows for removal of +\item{drop_trailing_zeros}{A logical value that allows for removal of trailing zeros (those redundant zeros after the decimal mark).} -\item{negative_val}{the formatting to use for negative values. With -\code{signed} (the default), negative values will be shown with a negative -sign. Using \code{parens} will show the negative value in parentheses.} - -\item{use_seps}{an option to use digit group separators. The type of digit +\item{use_seps}{An option to use digit group separators. The type of digit group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} -\item{scale_by}{a value to scale the input. The default is \code{1.0}.} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All +numeric values will be multiplied by this value first before undergoing +formatting. This value will be ignored if using any of the \code{suffixing} +options (i.e., where \code{suffixing} is not set to \code{FALSE}).} -\item{suffixing}{an option to scale and apply suffixes to larger numbers +\item{suffixing}{An option to scale and apply suffixes to larger numbers (e.g., \code{1924000} can be transformed to \code{1.92M}). This option can accept a logical value, where \code{FALSE} (the default) will not perform this transformation and \code{TRUE} will apply thousands (\code{K}), @@ -61,26 +60,27 @@ numbers in the range of millions and billions will be in terms of millions). Any use of \code{suffixing} (where not \code{FALSE}) means that any value provided to \code{scale_by} will be ignored.} -\item{pattern}{a formatting pattern that allows for decoration of the +\item{pattern}{A formatting pattern that allows for decoration of the formatted value. The value itself is represented by \code{{x}} and all other characters are taken to be string literals.} -\item{sep_mark}{the mark to use as a separator between groups of digits +\item{sep_mark}{The mark to use as a separator between groups of digits (e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value of \code{1,000}).} -\item{dec_mark}{the character to use as a decimal mark (e.g., using +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} -\item{locale}{an optional locale ID that can be used for formatting the value +\item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}.} +\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a +useful reference for all of the locales that are supported.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ With numeric values in a \pkg{gt} table, we can perform number-based @@ -90,8 +90,6 @@ over numeric formatting with the following options: \itemize{ \item decimals: choice of the number of decimal places, option to drop trailing zeros, and a choice of the decimal symbol -\item negative values: choice of a negative sign or parentheses for values -less than zero \item digit grouping separators: options to enable/disable digit separators and provide a choice of separator symbol \item scaling: we can choose to scale targeted values by a multiplier value diff --git a/man/fmt_passthrough.Rd b/man/fmt_passthrough.Rd index ccc171b502..889865bd27 100644 --- a/man/fmt_passthrough.Rd +++ b/man/fmt_passthrough.Rd @@ -8,17 +8,17 @@ fmt_passthrough(data, columns, rows = NULL, escape = TRUE, pattern = "{x}") } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -27,19 +27,19 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{escape}{an option to escape text according to the final output format +\item{escape}{An option to escape text according to the final output format of the table. For example, if a LaTeX table is to be generated then LaTeX escaping would be performed during rendering. By default this is set to \code{TRUE} and setting to \code{FALSE} is useful in the case where LaTeX-formatted text should be passed through to the output LaTeX table unchanged.} -\item{pattern}{a formatting pattern that allows for decoration of the +\item{pattern}{A formatting pattern that allows for decoration of the formatted value. The value itself is represented by \code{{x}} and all other characters are taken to be string literals.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Format by passing data through no other transformation other than: (1) diff --git a/man/fmt_percent.Rd b/man/fmt_percent.Rd index e6722a6032..8a99e6969d 100644 --- a/man/fmt_percent.Rd +++ b/man/fmt_percent.Rd @@ -5,22 +5,22 @@ \title{Format values as a percentage} \usage{ fmt_percent(data, columns, rows = NULL, decimals = 2, - drop_trailing_zeros = FALSE, negative_val = "signed", - use_seps = TRUE, pattern = "{x}", sep_mark = ",", dec_mark = ".", - incl_space = FALSE, placement = "right", locale = NULL) + drop_trailing_zeros = FALSE, use_seps = TRUE, pattern = "{x}", + sep_mark = ",", dec_mark = ".", incl_space = FALSE, + placement = "right", locale = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -29,43 +29,40 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{decimals}{an option to specify the exact number of decimal places to +\item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} -\item{drop_trailing_zeros}{a logical value that allows for removal of +\item{drop_trailing_zeros}{A logical value that allows for removal of trailing zeros (those redundant zeros after the decimal mark).} -\item{negative_val}{the formatting to use for negative values. With -\code{signed} (the default), negative values will be shown with a negative -sign. Using \code{parens} will show the negative value in parentheses.} - -\item{use_seps}{an option to use digit group separators. The type of digit +\item{use_seps}{An option to use digit group separators. The type of digit group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} -\item{pattern}{a formatting pattern that allows for decoration of the +\item{pattern}{A formatting pattern that allows for decoration of the formatted value. The value itself is represented by \code{{x}} and all other characters are taken to be string literals.} -\item{sep_mark}{the mark to use as a separator between groups of digits +\item{sep_mark}{The mark to use as a separator between groups of digits (e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value of \code{1,000}).} -\item{dec_mark}{the character to use as a decimal mark (e.g., using +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} -\item{incl_space}{an option on whether to include a space between the value +\item{incl_space}{An option for whether to include a space between the value and the percent sign. The default is to not introduce a space character.} -\item{placement}{the placement of the percent sign. This can be either be +\item{placement}{The placement of the percent sign. This can be either be \code{right} (the default) or \code{left}.} -\item{locale}{an optional locale ID that can be used for formatting the value +\item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}.} +\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a +useful reference for all of the locales that are supported.} } \value{ an object of class \code{gt_tbl}. @@ -82,8 +79,6 @@ before the values and a space can be inserted between the symbol and the value. \item decimals: choice of the number of decimal places, option to drop trailing zeros, and a choice of the decimal symbol -\item negative values: choice of a negative sign or parentheses for values -less than zero \item digit grouping separators: options to enable/disable digit separators and provide a choice of separator symbol \item pattern: option to use a text pattern for decoration of the formatted diff --git a/man/fmt_scientific.Rd b/man/fmt_scientific.Rd index 458ad5823f..28d7aa20f1 100644 --- a/man/fmt_scientific.Rd +++ b/man/fmt_scientific.Rd @@ -9,17 +9,17 @@ fmt_scientific(data, columns, rows = NULL, decimals = 2, sep_mark = ",", dec_mark = ".", locale = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -28,34 +28,38 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{decimals}{an option to specify the exact number of decimal places to +\item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} -\item{drop_trailing_zeros}{a logical value that allows for removal of +\item{drop_trailing_zeros}{A logical value that allows for removal of trailing zeros (those redundant zeros after the decimal mark).} -\item{scale_by}{a value to scale the input. The default is \code{1.0}.} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All +numeric values will be multiplied by this value first before undergoing +formatting. This value will be ignored if using any of the \code{suffixing} +options (i.e., where \code{suffixing} is not set to \code{FALSE}).} -\item{pattern}{a formatting pattern that allows for decoration of the +\item{pattern}{A formatting pattern that allows for decoration of the formatted value. The value itself is represented by \code{{x}} and all other characters are taken to be string literals.} -\item{sep_mark}{the mark to use as a separator between groups of digits +\item{sep_mark}{The mark to use as a separator between groups of digits (e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value of \code{1,000}).} -\item{dec_mark}{the character to use as a decimal mark (e.g., using +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} -\item{locale}{an optional locale ID that can be used for formatting the value +\item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}.} +\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a +useful reference for all of the locales that are supported.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ With numeric values in a \pkg{gt} table, we can perform formatting so that the diff --git a/man/fmt_time.Rd b/man/fmt_time.Rd index f3d52ecce9..7569b2af22 100644 --- a/man/fmt_time.Rd +++ b/man/fmt_time.Rd @@ -7,17 +7,17 @@ fmt_time(data, columns, rows = NULL, time_style = 2) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} -\item{columns}{the columns to format. Can either be a series of column names +\item{columns}{The columns to format. Can either be a series of column names provided in \code{vars()}, a vector of column indices, or a helper function focused on selections. The select helper functions are: \code{\link{starts_with}()}, \code{\link{ends_with}()}, \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, and \code{\link{everything}()}.} -\item{rows}{optional rows to format. Not providing any value results in all +\item{rows}{Optional rows to format. Not providing any value results in all rows in \code{columns} being formatted. Can either be a vector of row captions provided \code{c()}, a vector of row indices, or a helper function focused on selections. The select helper functions are: @@ -26,11 +26,14 @@ focused on selections. The select helper functions are: and \code{\link{everything}()}. We can also use expressions to filter down to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} -\item{time_style}{the time style to use. Supply a number (from \code{1} to +\item{time_style}{The time style to use. Supply a number (from \code{1} to \code{5}) that corresponds to the preferred time style. Use \code{\link{info_time_style}()} to see the different numbered and named time presets.} } +\value{ +An object of class \code{gt_tbl}. +} \description{ Format input time values that are character-based and expressed according to the ISO 8601 time format (\code{HH:MM:SS}). Once the appropriate data cells diff --git a/man/tab_footnote.Rd b/man/tab_footnote.Rd index 12e3aa46ca..d9644360da 100644 --- a/man/tab_footnote.Rd +++ b/man/tab_footnote.Rd @@ -7,7 +7,7 @@ tab_footnote(data, footnote, locations) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{footnote}{the text to be used in the footnote. We can optionally use diff --git a/man/tab_header.Rd b/man/tab_header.Rd index 32b6b29d35..9c76a43d97 100644 --- a/man/tab_header.Rd +++ b/man/tab_header.Rd @@ -7,7 +7,7 @@ tab_header(data, title, subtitle = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{title, subtitle}{text to be used in the table title and, optionally, for diff --git a/man/tab_options.Rd b/man/tab_options.Rd index 478e48f6ac..d7e22f59ec 100644 --- a/man/tab_options.Rd +++ b/man/tab_options.Rd @@ -35,7 +35,7 @@ tab_options(data, table.width = NULL, table.font.size = NULL, row.striping.include_table_body = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{table.width}{the width of the table. Can be specified as a diff --git a/man/tab_row_group.Rd b/man/tab_row_group.Rd index e8b82fde89..43c897fb26 100644 --- a/man/tab_row_group.Rd +++ b/man/tab_row_group.Rd @@ -7,7 +7,7 @@ tab_row_group(data, group = NULL, rows = NULL, others = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{group}{the name of the row group. This text will also serve as the row diff --git a/man/tab_source_note.Rd b/man/tab_source_note.Rd index 71a2f0f328..00467ad610 100644 --- a/man/tab_source_note.Rd +++ b/man/tab_source_note.Rd @@ -7,7 +7,7 @@ tab_source_note(data, source_note) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{source_note}{text to be used in the source note. We can optionally use diff --git a/man/tab_spanner.Rd b/man/tab_spanner.Rd index 9bd2ac9893..ccf94a1d4b 100644 --- a/man/tab_spanner.Rd +++ b/man/tab_spanner.Rd @@ -7,7 +7,7 @@ tab_spanner(data, label, columns, gather = TRUE) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{label}{the text to use for the spanner column label.} diff --git a/man/tab_stubhead_label.Rd b/man/tab_stubhead_label.Rd index c33bf45902..9e1156e9ad 100644 --- a/man/tab_stubhead_label.Rd +++ b/man/tab_stubhead_label.Rd @@ -7,7 +7,7 @@ tab_stubhead_label(data, label) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{label}{the text to be used as the stubhead label We can optionally diff --git a/man/tab_style.Rd b/man/tab_style.Rd index f9e70af555..5d0f9d6584 100644 --- a/man/tab_style.Rd +++ b/man/tab_style.Rd @@ -7,7 +7,7 @@ tab_style(data, style, locations) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{A table object that is created using the \code{\link{gt}()} function.} \item{style}{a vector of styles to use. The \code{\link{cells_styles}()} diff --git a/tests/testthat/test-fmt_currency.R b/tests/testthat/test-fmt_currency.R index bf41ff1f4f..a67d2e698a 100644 --- a/tests/testthat/test-fmt_currency.R +++ b/tests/testthat/test-fmt_currency.R @@ -141,10 +141,10 @@ test_that("the `fmt_currency()` function works correctly", { expect_equal( (tab %>% fmt_currency( - columns = "num_1", currency = "USD", negative_val = "parens") %>% + columns = "num_1", currency = "USD", accounting = TRUE) %>% render_formats_test("html"))[["num_1"]], c("$1,836.23", "$2,763.39", "$937.29", "$643.00", "$212.23", - "$0.00", "($23.24)") + "$0.00", "($23.24)") ) # Format the `num_1` column as USD, apply parentheses to all negative @@ -153,7 +153,7 @@ test_that("the `fmt_currency()` function works correctly", { expect_equal( (tab %>% fmt_currency( - columns = "num_1", currency = "USD", negative_val = "parens") %>% + columns = "num_1", currency = "USD", accounting = TRUE) %>% render_formats_test("default"))[["num_1"]], c("$1,836.23", "$2,763.39", "$937.29", "$643.00", "$212.23", "$0.00", "($23.24)") diff --git a/tests/testthat/test-fmt_number.R b/tests/testthat/test-fmt_number.R index f0541371b3..ceb126556e 100644 --- a/tests/testthat/test-fmt_number.R +++ b/tests/testthat/test-fmt_number.R @@ -110,15 +110,6 @@ test_that("the `fmt_number()` function works correctly", { render_formats_test("html"))[["num_1"]], c("1.836,23", "2.763,39", "937,29", "643,00", "212,23", "0,00", "−23,24")) - # Format the `num_1` column to 2 decimal places, apply parentheses to - # all negative values, use all other defaults; extract `output_df` and - # compare to expected values - expect_equal( - (tab %>% - fmt_number(columns = "num_1", decimals = 2, negative_val = "parens") %>% - render_formats_test("html"))[["num_1"]], - c("1,836.23", "2,763.39", "937.29", "643.00", "212.23", "0.00", "(23.24)")) - # Format the `num_1` column to 4 decimal places, scale all values by # 1/1000, use all other defaults; extract `output_df` and compare # to expected values diff --git a/tests/testthat/test-fmt_percent.R b/tests/testthat/test-fmt_percent.R index feb7f42f19..1264b17e2b 100644 --- a/tests/testthat/test-fmt_percent.R +++ b/tests/testthat/test-fmt_percent.R @@ -103,18 +103,6 @@ test_that("the `fmt_percent()` function works correctly", { "−2.324,00%") ) - # Format the `num_1` column to 2 decimal places, apply parentheses to - # all negative values, use all other defaults; extract `output_df` and - # compare to expected values - expect_equal( - (tab %>% - fmt_percent(columns = "num_1", decimals = 2, negative_val = "parens") %>% - render_formats_test("html"))[["num_1"]], - c("183,623.00%", "276,339.00%", "93,729.00%", - "64,300.00%", "21,223.20%", "0.00%", - "(2,324.00%)") - ) - # Format the `num_1` column to 2 decimal places, prepend and append # all values by 2 different literals, use all other defaults; extract # `output_df` and compare to expected values @@ -151,7 +139,7 @@ test_that("the `fmt_percent()` function works correctly", { render_formats_test("html"))[["num_1"]], c("% 183,623", "% 276,339", "% 93,729", "% 64,300", "% 21,223", "% 0", - "% −2,324") + "−% 2,324") ) # Format the `num_1` column to 2 decimal places, apply the `en_US` diff --git a/tests/testthat/test-l_fmt_currency.R b/tests/testthat/test-l_fmt_currency.R index 8fe17bbdeb..32f0994fb4 100644 --- a/tests/testthat/test-l_fmt_currency.R +++ b/tests/testthat/test-l_fmt_currency.R @@ -98,11 +98,11 @@ test_that("the `fmt_currency()` function works correctly", { expect_equal( (tbl_latex %>% fmt_currency( - columns = "num_1", currency = "USD", negative_val = "parens") %>% + columns = "num_1", currency = "USD", accounting = TRUE) %>% render_formats_test("latex"))[["num_1"]], c("$\\text{\\$}1,836.23$", "$\\text{\\$}2,763.39$", "$\\text{\\$}937.29$", "$\\text{\\$}643.00$", "$\\text{\\$}212.23$", "$\\text{\\$}0.00$", - "$\\left(\\text{\\$}23.24\\right)$") + "$(\\text{\\$}23.24)$") ) # Format the `num_1` column as USD, apply parentheses to all negative @@ -111,11 +111,11 @@ test_that("the `fmt_currency()` function works correctly", { expect_equal( (tbl_latex %>% fmt_currency( - columns = "num_1", currency = "USD", negative_val = "parens") %>% + columns = "num_1", currency = "USD", accounting = TRUE) %>% render_formats_test("latex"))[["num_1"]], c("$\\text{\\$}1,836.23$", "$\\text{\\$}2,763.39$", "$\\text{\\$}937.29$", "$\\text{\\$}643.00$", "$\\text{\\$}212.23$", "$\\text{\\$}0.00$", - "$\\left(\\text{\\$}23.24\\right)$") + "$(\\text{\\$}23.24)$") ) # Format the `num_1` column as USD to 4 decimal places, scale all values by diff --git a/tests/testthat/test-l_fmt_number.R b/tests/testthat/test-l_fmt_number.R index bb980cafc9..cdef2ddc33 100644 --- a/tests/testthat/test-l_fmt_number.R +++ b/tests/testthat/test-l_fmt_number.R @@ -89,17 +89,6 @@ test_that("the `fmt_number()` function works correctly", { "$212,23$", "$0,00$", "$-23,24$") ) - # Format the `num_1` column to 2 decimal places, apply parentheses to - # all negative values, use all other defaults; extract `output_df` and - # compare to expected values - expect_equal( - (tbl_latex %>% - fmt_number(columns = "num_1", decimals = 2, negative_val = "parens") %>% - render_formats_test("latex"))[["num_1"]], - c("$1,836.23$", "$2,763.39$", "$937.29$", "$643.00$", - "$212.23$", "$0.00$", "$(23.24)$") - ) - # Format the `num_1` column to 4 decimal places, scale all values by # 1/1000, use all other defaults; extract `output_df` and compare # to expected values diff --git a/tests/testthat/test-l_fmt_percent.R b/tests/testthat/test-l_fmt_percent.R index 20d7d4c8e5..8f841ad68e 100644 --- a/tests/testthat/test-l_fmt_percent.R +++ b/tests/testthat/test-l_fmt_percent.R @@ -90,17 +90,6 @@ test_that("the `fmt_percent()` function works correctly", { "$21.223,20\\%$", "$0,00\\%$", "$-2.324,00\\%$") ) - # Format the `num_1` column to 2 decimal places, apply parentheses to - # all negative values, use all other defaults; extract `output_df` and - # compare to expected values - expect_equal( - (tbl_latex %>% - fmt_percent(columns = "num_1", decimals = 2, negative_val = "parens") %>% - render_formats_test("latex"))[["num_1"]], - c("$183,623.00\\%$", "$276,339.00\\%$", "$93,729.00\\%$", "$64,300.00\\%$", - "$21,223.20\\%$", "$0.00\\%$", "$\\left(2,324.00\\%\\right)$") - ) - # Format the `num_1` column to 2 decimal places, prepend and append # all values by 2 different literals, use all other defaults; extract # `output_df` and compare to expected values @@ -138,7 +127,7 @@ test_that("the `fmt_percent()` function works correctly", { ) %>% render_formats_test("latex"))[["num_1"]], c("$\\% 183,623$", "$\\% 276,339$", "$\\% 93,729$", "$\\% 64,300$", - "$\\% 21,223$", "$\\% 0$", "$\\% -2,324$") + "$\\% 21,223$", "$\\% 0$", "$-\\% 2,324$") ) # Format the `num_1` column to 2 decimal places, apply the `en_US` From 9aeb069817492f3dfb26cf66c07aeead82e48534 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Wed, 24 Apr 2019 14:06:10 -0400 Subject: [PATCH 3/8] Modify _travis.yml (#263) * Modify _travis.yml * Add yaml pipe for text block --- .travis.yml | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 332fb7bb81..8264bd538e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,9 +2,15 @@ language: R sudo: false -cache: packages +cache: + packages: true warnings_are_errors: false +r: + - oldrel + - release + - devel + notifications: email: on_success: change @@ -12,14 +18,11 @@ notifications: jobs: include: - - stage: "R CMD check" - r: oldrel - - r: release - - r: devel - - stage: deploy name: covr r: release + cache: + packages: false r_binary_packages: - covr script: @@ -28,13 +31,19 @@ jobs: - stage: deploy name: pkgdown r: release - if: branch IN (master) + cache: + packages: false + if: | + branch IN (master, travis) AND \ + type = push AND \ + repo = rstudio/gt r_binary_packages: - pkgdown + - remotes script: - - Rscript -e "devtools::install()" + - Rscript -e "remotes::install_local()" - Rscript -e "pkgdown::build_site()" - - Rscript -e "remove.packages(devtools::as.package('.')$package)" + - Rscript -e "remove.packages('gt')" deploy: provider: pages local-dir: docs From 85a9e74a37e14fe4f523182edc953f0ec54382d2 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Wed, 24 Apr 2019 19:03:09 -0400 Subject: [PATCH 4/8] Bugfixes and improvements to `summary_rows()` (#175) * Add comments * Simplify assignment * Modify comments * Simplify assignment * Add `select()` statement * Modify object names * Remove `select()` statement * Refactor function * Make correction to conditional stmt * Equate `groups == FALSE` to NULL * Refactor and allow for specialized grand summary grp * Append grand summary rows to bottom of body * Add CSS class for the first grand summary row * Update tests to reflect new behavior * Include a `context` argument * Normalize `groups` and stop early if necessary * Modify special label used for grand summary * Use `rlang::as_closure()` instead of `rlang::as_function()` * Refactor statements that produce summary labels * Stop function if summary labels are not unique * Modify call to `create_summary_dfs()` * Modify call to `create_summary_dfs()` * Refactor the `extract_summary()` function * Modify roxygen documentation * Modify default value of `groups` arg * Update help file using roxygen * Stop function if names are not given for bare fcns * Modify label used * Remove background color for stub * Add CSS rule for grand summary rows * Apply Sass `font-color` function to summary rows * Add Sass rule for grand summary row color * Add options and defaults for grand summary rows * Add the `cells_grand_summary()` function * Modify default options for `summary_rows()` * Modify the `tab_options()` function * Add util functions to support grand summaries * Update help files using roxygen * Add to NAMESPACE * Modify tests to reflect new behavior * Allow for stub creation when necessary * Add several tests for `summary_rows()` * Modify roxygen @param statement * Modify roxygen @param statement * Update help file using roxygen * Modify roxygen description text * Modify roxygen description text * Update help file using roxygen * Modify assignment to df * Use `resolve_vars()` to obtain colnames * Obtain and store labels in `summary_rows()` * Revise `*.cells_summary` to use multiple expr types * Revise `*.cells_grand_summary` to use multiple expr types * Modify several testthat tests * Update help file using roxygen * Simplify statements * Modify roxygen documentation * Update help file using roxygen * Get `labels` from `summary_attrs` * Assign identifier string to local variable * Add the `assert_rowgroups()` function * Add calls the `assert_rowgroups()` fcn * Remove statements to obtain row labels * Replace identifier string with local variable * Remove `subset()` statements * Refactor `lapply()` statements * Add tests for `cells_summary()` * Add tests for `cells_grand_summary()` * Add tests for `tab_footnote()` * Use the internal `is_false()` fcn * Modify the `is_false()` call * Add several testthat tests * Add tests for the `tab_style()` fcn * Refactor some `set_style.*()` fcns * Add tests for the `tab_options()` fcn * Add several testthat tests * Refactor the adding of summary location rows * Add the `tidy_sub()` util function * Add the `context_missing_text()` util function * Refactor the `cols_merge_range()` function * Use the `context_dash_mark()` function * Use the `context_missing_text()` function * Modify the `perform_col_merge()` fcn call * Make corrections to several testthat tests * Ensure sep is an empty string * Remove unneeded conditional statement * Create `grand_summary_col` variable * Modify position of check for labels (earlier) * Clean up logic of checks for groups * Use `lapply()` statement in refactor * Do not hardcode HTML formatter * Use `grand_summary_col` variable --- NAMESPACE | 1 + R/as_rtf.R | 6 +- R/build_data.R | 6 +- R/extract_summary.R | 89 +-- R/format_data.R | 10 +- R/gt_options_default.R | 7 +- R/helpers.R | 24 + R/modify_columns.R | 11 +- R/summary_rows.R | 258 +++++-- R/tab_footnote.R | 29 +- R/tab_options.R | 41 +- R/tab_style.R | 29 +- R/utils.R | 14 +- R/utils_formatters.R | 34 + R/utils_render_common.R | 206 +++--- R/utils_render_footnotes.R | 102 ++- R/utils_render_html.R | 104 ++- inst/css/gt_colors.scss | 1 + inst/css/gt_styles_default.scss | 17 +- man/location_cells.Rd | 3 + man/summary_rows.Rd | 56 +- man/tab_options.Rd | 19 +- tests/testthat/test-cols_merge.R | 14 +- tests/testthat/test-conditional_fmt.R | 2 +- tests/testthat/test-fmt_missing.R | 10 +- tests/testthat/test-l_cols_merge.R | 60 +- tests/testthat/test-location_cells.R | 63 +- tests/testthat/test-summary_rows.R | 926 +++++++++++++++++++++++--- tests/testthat/test-tab_footnote.R | 304 ++++++++- tests/testthat/test-tab_options.R | 50 +- tests/testthat/test-tab_style.R | 72 ++ tests/testthat/test-table_parts.R | 16 + tests/testthat/test-util_functions.R | 4 +- 33 files changed, 2127 insertions(+), 461 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 259bc361fc..096f6d8a7e 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -8,6 +8,7 @@ export(as_raw_html) export(as_rtf) export(cells_column_labels) export(cells_data) +export(cells_grand_summary) export(cells_group) export(cells_stub) export(cells_styles) diff --git a/R/as_rtf.R b/R/as_rtf.R index 5d818dfc20..74377f58c9 100644 --- a/R/as_rtf.R +++ b/R/as_rtf.R @@ -179,7 +179,9 @@ as_rtf <- function(data) { # Perform any necessary column merge operations col_merge_output <- - perform_col_merge(col_merge, data_df, output_df, boxh_df, columns_df) + perform_col_merge( + col_merge, data_df, output_df, boxh_df, columns_df, context + ) # Rewrite `output_df`, `boxh_df`, and `columns_df` as a result of merging output_df <- col_merge_output$output_df @@ -188,7 +190,7 @@ as_rtf <- function(data) { # Create the `list_of_summaries` list of lists list_of_summaries <- - create_summary_dfs(summary_list, data_df, stub_df, output_df) + create_summary_dfs(summary_list, data_df, stub_df, output_df, context) # Determine if there is a populated stub stub_available <- is_stub_available(stub_df) diff --git a/R/build_data.R b/R/build_data.R index f9eac167d5..d10263b023 100644 --- a/R/build_data.R +++ b/R/build_data.R @@ -156,7 +156,9 @@ build_data <- function(data, context) { # Perform any necessary column merge operations col_merge_output <- - perform_col_merge(col_merge, data_df, output_df, boxh_df, columns_df) + perform_col_merge( + col_merge, data_df, output_df, boxh_df, columns_df, context + ) # Rewrite `output_df`, `boxh_df`, and `columns_df` as a result of merging output_df <- col_merge_output$output_df @@ -165,7 +167,7 @@ build_data <- function(data, context) { # Create the `list_of_summaries` list of lists list_of_summaries <- - create_summary_dfs(summary_list, data_df, stub_df, output_df) + create_summary_dfs(summary_list, data_df, stub_df, output_df, context) # Determine if there is a populated stub stub_available <- is_stub_available(stub_df) diff --git a/R/extract_summary.R b/R/extract_summary.R index 9265bc4172..53af783603 100644 --- a/R/extract_summary.R +++ b/R/extract_summary.R @@ -59,86 +59,23 @@ #' @export extract_summary <- function(data) { - # Extract all attributes from the data object into `data_attr` + # Extract all attributes from the `data` + # object into `data_attr` data_attr <- attributes(data) + # Stop function if there are no + # directives to create summary rows if (is.null(data_attr$summary)) { - stop("There is no summary data frame to extract.", call. = FALSE) + stop("There is no summary list to extract.\n", + "Use the `summary_rows()` function to generate summaries.", + call. = FALSE) } - # Move original data frame to `data_df` - data_df <- as.data.frame(data) + # Build the `data` using the standard + # pipeline with the `html` context + built_data <- build_data(data = data, context = "html") - # Get the `boxh_df` data frame - boxh_df <- data_attr$boxh_df - - # Get the `stub_df` data frame - stub_df <- data_attr$stub_df - - # Get the `rows_df` data frame - rows_df <- data_attr$rows_df - - # Get the `cols_df` data frame - cols_df <- data_attr$cols_df - - # Get the `formats` list - formats <- data_attr$formats - - # Get the `arrange_groups` vector - arrange_groups <- data_attr$arrange_groups - - # Get the `others_group` vector - others_group <- data_attr$others_group[[1]] %||% NA_character_ - - # Get the `col_merge` object - col_merge <- data_attr$col_merge - - # Get the `summary_list` object - summary_list <- data_attr$summary - - # Initialize `output_df` - output_df <- initialize_output_df(data_df) - - # Create `output_df` with rendered values - output_df <- render_formats(output_df, data_df, formats, context = "html") - - # Move input data cells to `output_df` that didn't have - # any rendering applied during `render_formats()` - output_df <- migrate_unformatted_to_output(data_df, output_df, context = "html") - - # Get the reordering df (`rows_df`) for the data rows - rows_df <- get_row_reorder_df(arrange_groups, stub_df) - - # Get the `columns_df` data frame for the data columns - columns_df <- get_column_reorder_df(cols_df, boxh_df) - - # Reassemble the rows and columns of `data_df` in the correct order - output_df <- reassemble_output_df(output_df, rows_df, columns_df) - - # Get the `groups_df` data frame, which is a rearranged representation - # of the stub `groupname` and `rowname` columns - groups_df <- get_groupnames_rownames_df(stub_df, rows_df) - - # Replace NA values in the `groupname` column if there is a reserved - # label for the unlabeled group - groups_df[is.na(groups_df[, "groupname"]), "groupname"] <- others_group - - # Create the `groups_rows_df` data frame, which provides information - # on which rows the group rows should appear above - groups_rows_df <- get_groups_rows_df(arrange_groups, groups_df) - - # Perform any necessary column merge operations - col_merge_output <- - perform_col_merge(col_merge, data_df, output_df, boxh_df, columns_df) - - # Rewrite `output_df`, `boxh_df`, and `columns_df` as a result of merging - output_df <- col_merge_output$output_df - boxh_df <- col_merge_output$boxh_df - columns_df <- col_merge_output$columns_df - - # Create the `list_of_summaries` list of lists - list_of_summaries <- - create_summary_dfs(summary_list, data_df, stub_df, output_df) - - list_of_summaries$summary_df_data_list + # Extract the list of summary data frames + # that contains tidy, unformatted data + built_data$list_of_summaries$summary_df_data_list } diff --git a/R/format_data.R b/R/format_data.R index 9ff58d01ed..828388f595 100644 --- a/R/format_data.R +++ b/R/format_data.R @@ -1294,11 +1294,11 @@ fmt_missing <- function(data, fns = list( html = function(x) { - if (missing_text == "---") { - missing_text <- "\u2014" - } else if (missing_text == "--") { - missing_text <- "\u2013" - } + missing_text <- + context_missing_text( + missing_text = missing_text, + context = "html" + ) # Any values of `x` that are `NA` get # `missing_text` as output; any values that diff --git a/R/gt_options_default.R b/R/gt_options_default.R index 555211ea70..c465f656fb 100644 --- a/R/gt_options_default.R +++ b/R/gt_options_default.R @@ -33,12 +33,15 @@ gt_options_default <- function() { "table_body_border_bottom_style", TRUE, "table_body", "solid", "table_body_border_bottom_width", TRUE, "table_body", "2px", "table_body_border_bottom_color", TRUE, "table_body", "#A8A8A8", - "row_padding", TRUE, "row", "10px", + "row_padding", TRUE, "row", "8px", "row_striping_include_stub", TRUE, "row", "TRUE", "row_striping_include_table_body", TRUE, "row", "TRUE", "summary_row_background_color", TRUE, "summary_row", NA_character_, - "summary_row_padding", TRUE, "summary_row", "6px", + "summary_row_padding", TRUE, "summary_row", "8px", "summary_row_text_transform", TRUE, "summary_row", "inherit", + "grand_summary_row_background_color", TRUE, "grand_summary_row", NA_character_, + "grand_summary_row_padding", TRUE, "grand_summary_row", "8px", + "grand_summary_row_text_transform", TRUE, "grand_summary_row", "inherit", "footnote_sep", FALSE, "footnote", "
", "footnote_glyph", FALSE, "footnote", "numbers", "footnote_font_size", TRUE, "footnote", "90%", diff --git a/R/helpers.R b/R/helpers.R index 4bd858b25a..b6fbfbf271 100644 --- a/R/helpers.R +++ b/R/helpers.R @@ -364,6 +364,30 @@ cells_summary <- function(groups = NULL, cells } +#' @rdname location_cells +#' @import rlang +#' @export +cells_grand_summary <- function(columns = NULL, + rows = NULL) { + + # Capture expressions for the `columns` + # and `rows` arguments + col_expr <- rlang::enquo(columns) + row_expr <- rlang::enquo(rows) + + # Create the `cells_grand_summary` object + cells <- + list( + columns = col_expr, + rows = row_expr) + + # Apply the `cells_grand_summary` and + # `location_cells` classes + class(cells) <- c("cells_grand_summary", "location_cells") + + cells +} + #' Interpret input text as Markdown-formatted text #' @param text the text that is understood to contain Markdown formatting. #' @return a character object that is tagged for a Markdown-to-HTML diff --git a/R/modify_columns.R b/R/modify_columns.R index 1bf79c7711..d89a97c4a5 100644 --- a/R/modify_columns.R +++ b/R/modify_columns.R @@ -767,6 +767,7 @@ cols_merge <- function(data, attr(data, "col_merge") <- list( pattern = pattern, + sep = "", col_1 = col_1) } @@ -885,6 +886,7 @@ cols_merge_uncert <- function(data, attr(data, "col_merge") <- list( pattern = pattern, + sep = "", col_1 = col_val) } @@ -962,10 +964,11 @@ cols_merge_uncert <- function(data, #' @export cols_merge_range <- function(data, col_begin, - col_end) { + col_end, + sep = "---") { # Set the formatting pattern - pattern <- "{1} \u2014 {2}" + pattern <- "{1} {sep} {2}" col_begin <- enquo(col_begin) col_end <- enquo(col_end) @@ -991,6 +994,9 @@ cols_merge_range <- function(data, attr(data, "col_merge")[["pattern"]] <- c(attr(data, "col_merge")[["pattern"]], pattern) + attr(data, "col_merge")[["sep"]] <- + c(attr(data, "col_merge")[["sep"]], sep) + attr(data, "col_merge")[["col_1"]] <- c(attr(data, "col_merge")[["col_1"]], col_begin) @@ -999,6 +1005,7 @@ cols_merge_range <- function(data, attr(data, "col_merge") <- list( pattern = pattern, + sep = sep, col_1 = col_begin) } diff --git a/R/summary_rows.R b/R/summary_rows.R index 71933ceb02..db345bc761 100644 --- a/R/summary_rows.R +++ b/R/summary_rows.R @@ -1,39 +1,49 @@ #' Add summary rows using aggregation functions #' -#' Add summary rows to one or more row groups by using the input data already -#' provided in the \code{\link{gt}()} function alongside any suitable -#' aggregation functions. Should we need to obtain the summary data for external -#' purposes, the \code{\link{extract_summary}()} can be used with a -#' \code{gt_tbl} object where summary rows were added via \code{summary_rows()}. -#' @param data a table object that is created using the \code{gt()} function. -#' @param groups the row groups labels that identify which summary rows will be -#' added. -#' @param columns the columns for which the summaries should be calculated. If -#' nothing is provided, then the supplied aggregation functions will be -#' applied to all columns. -#' @param fns functions used for aggregations. This can include base functions +#' Add groupwise summary rows to one or more row groups by using the input data +#' already provided in the \code{\link{gt}()} function alongside any suitable +#' aggregation functions. Or, add a grand summary that incorporates all +#' available data, regardless of grouping. You choose how to format the values +#' in the resulting summary cells by use of a \code{formatter} function (e.g, +#' \code{\link{fmt_number}()}) and any relevant options. +#' +#' Should we need to obtain the summary data for external purposes, the +#' \code{\link{extract_summary}()} function can be used with a \code{gt_tbl} +#' object where summary rows were added via \code{summary_rows()}. +#' +#' @param data A table object that is created using the \code{gt()} function. +#' @param groups The groups to consider for generation of groupwise summary +#' rows. By default this is set to \code{NULL}, which results in the formation +#' of grand summary rows (a grand summary operates on all table data). +#' Providing the names of row groups in \code{c()} will create a groupwise +#' summary and generate summary rows for the specified groups. Setting this to +#' \code{TRUE} indicates that all available groups will receive groupwise +#' summary rows. +#' @param columns The columns for which the summaries should be calculated. +#' @param fns Functions used for aggregations. This can include base functions #' like \code{mean}, \code{min}, \code{max}, \code{median}, \code{sd}, or #' \code{sum} or any other user-defined aggregation function. The function(s) #' should be supplied within a \code{list()}. Within that list, we can specify -#' the functions by use of function names (e.g., \code{"sum"}), the functions -#' themselves (e.g., \code{sum}), or one-sided R formulas by prefacing with a -#' \code{~} where \code{.} serves as the data to be summarized (e.g., -#' \code{sum(., na.rm = TRUE)}). By using named arguments, the names will -#' serve as row labels for the corresponding summary rows (otherwise the -#' labels will be derived from the function names). -#' @param missing_text the text to be used in place of \code{NA} values in +#' the functions by use of function names in quotes (e.g., \code{"sum"}), as +#' bare functions (e.g., \code{sum}), or as one-sided R formulas using a +#' leading \code{~}. In the formula representation, a \code{.} serves as the +#' data to be summarized (e.g., \code{sum(., na.rm = TRUE)}). The use of named +#' arguments is recommended as the names will serve as summary row labels for +#' the corresponding summary rows data (the labels can derived from the +#' function names but only when not providing bare function names). +#' @param missing_text The text to be used in place of \code{NA} values in #' summary cells with no data outputs. -#' @param formatter a formatter function name. These can be any of the +#' @param formatter A formatter function name. These can be any of the #' \code{fmt_*()}functions available in the package (e.g., #' \code{\link{fmt_number}()}, \code{link{fmt_percent}()}, etc.), or a custom #' function using \code{\link{fmt}()}. The default function is #' \code{\link{fmt_number}()} and its options can be accessed through #' \code{...}. -#' @param ... values passed to the \code{formatter} function, where the provided +#' @param ... Values passed to the \code{formatter} function, where the provided #' values are to be in the form of named vectors. For example, when using the #' default \code{formatter} function, \code{\link{fmt_number}()}, options such #' as \code{decimals}, \code{use_seps}, and \code{locale} can be used. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class \code{gt_tbl}. #' @examples #' # Use `sp500` to create a gt table with #' # row groups; create summary rows (`min`, @@ -73,7 +83,7 @@ #' @export summary_rows <- function(data, groups = NULL, - columns = NULL, + columns = TRUE, fns, missing_text = "---", formatter = fmt_number, @@ -82,40 +92,206 @@ summary_rows <- function(data, # Collect all provided formatter options in a list formatter_options <- list(...) - if (is.null(groups)) { - groups <- TRUE + # If `groups` is FALSE, then do nothing; just + # return the `data` unchanged; having `groups` + # as `NULL` signifies a grand summary, `TRUE` + # is used for groupwise summaries across all + # groups + if (is_false(groups)) { + return(data) } - columns <- enquo(columns) + # Get the `stub_df` object from `data` + stub_df <- attr(data, "stub_df", exact = TRUE) + # Resolve the column names + columns <- enquo(columns) columns <- resolve_vars(var_expr = !!columns, data = data) - if ("summary" %in% names(attributes(data))) { + # If there isn't a stub available, create an + # 'empty' stub (populated with empty strings); + # the stub is necessary for summary row labels + if (!is_stub_available(stub_df) && is.null(groups)) { - attr(data, "summary") <- - c( - attr(data, "summary"), - list( - list( - groups = groups, - columns = columns, - fns = fns, - missing_text = missing_text, - formatter = formatter, - formatter_options = formatter_options))) + # Place the `rowname` values into `stub_df$rowname` + stub_df[["rowname"]] <- "" - } else { + attr(data, "stub_df") <- stub_df + } + + # Derive the summary labels + summary_labels <- + vapply(fns, derive_summary_label, FUN.VALUE = character(1)) - attr(data, "summary") <- + # If there are names, use those names + # as the summary labels + if (!is.null(names(summary_labels))) { + summary_labels <- names(summary_labels) + } + + # Append list of summary inputs to the + # `summary` attribute + attr(data, "summary") <- + c( + attr(data, "summary"), list( list( groups = groups, columns = columns, fns = fns, + summary_labels = summary_labels, missing_text = missing_text, formatter = formatter, - formatter_options = formatter_options)) + formatter_options = formatter_options + ) + ) + ) + + data +} + +add_summary_location_row <- function(loc, + data, + text, + df_type = "styles_df") { + + stub_df <- attr(data, "stub_df", exact = TRUE) + + row_groups <- + stub_df[, "groupname"] %>% + unique() + + summary_data <- attr(data, "summary", exact = TRUE) + + summary_data_summaries <- + vapply( + seq(summary_data), + function(x) !is.null(summary_data[[x]]$groups), + logical(1) + ) + + summary_data <- summary_data[summary_data_summaries] + + groups <- + row_groups[resolve_data_vals_idx( + var_expr = !!loc$groups, + data = NULL, + vals = row_groups + )] + + # Adding styles to intersections of group, row, and column; any + # that are missing at render time will be ignored + for (group in groups) { + + summary_labels <- + lapply( + summary_data, + function(summary_data_item) { + if (isTRUE(summary_data_item$groups)) { + summary_data_item$summary_labels + } else if (group %in% summary_data_item$groups){ + summary_data_item$summary_labels + } + } + ) %>% + unlist() %>% + unique() + + columns <- + resolve_vars( + var_expr = !!loc$columns, + data = data + ) + + if (length(columns) == 0) { + stop("The location requested could not be resolved:\n", + " * Review the expression provided as `columns`", + call. = FALSE) + } + + rows <- + resolve_data_vals_idx( + var_expr = !!loc$rows, + data = NULL, + vals = summary_labels + ) + + if (length(rows) == 0) { + stop("The location requested could not be resolved:\n", + " * Review the expression provided as `rows`", + call. = FALSE) + } + + attr(data, df_type) <- + add_location_row( + data, + df_type = df_type, + locname = "summary_cells", + locnum = 5, + grpname = group, + colname = columns, + rownum = rows, + text = text + ) + } + + data +} + +add_grand_summary_location_row <- function(loc, + data, + text, + df_type = "styles_df") { + + summary_data <- attr(data, "summary", exact = TRUE) + + grand_summary_labels <- + lapply(summary_data, function(summary_data_item) { + if (is.null(summary_data_item$groups)) { + return(summary_data_item$summary_labels) + } + + NULL + }) %>% + unlist() %>% + unique() + + columns <- + resolve_vars( + var_expr = !!loc$columns, + data = data + ) + + if (length(columns) == 0) { + stop("The location requested could not be resolved:\n", + " * Review the expression provided as `columns`", + call. = FALSE) } + rows <- + resolve_data_vals_idx( + var_expr = !!loc$rows, + data = NULL, + vals = grand_summary_labels + ) + + if (length(rows) == 0) { + stop("The location requested could not be resolved:\n", + " * Review the expression provided as `rows`", + call. = FALSE) + } + + attr(data, df_type) <- + add_location_row( + data, + df_type = df_type, + locname = "grand_summary_cells", + locnum = 6, + grpname = NA_character_, + colname = columns, + rownum = rows, + text = text + ) + data } diff --git a/R/tab_footnote.R b/R/tab_footnote.R index 937d93beb4..eaee3b47dd 100644 --- a/R/tab_footnote.R +++ b/R/tab_footnote.R @@ -200,23 +200,22 @@ set_footnote.cells_title <- function(loc, data, footnote) { set_footnote.cells_summary <- function(loc, data, footnote) { - groups <- (loc$groups %>% as.character())[-1] - rows <- (loc$rows %>% as.character())[-1] %>% as.integer() - - resolved <- resolve_cells_column_labels(data = data, object = loc) - - cols <- resolved$columns - - colnames <- colnames(as.data.frame(data))[cols] + add_summary_location_row( + loc = loc, + data = data, + text = footnote, + df_type = "footnotes_df" + ) +} - attr(data, "footnotes_df") <- - add_location_row( - data, df_type = "footnotes_df", - locname = "summary_cells", locnum = 5, - grpname = groups, colname = colnames, - rownum = rows, text = footnote) +set_footnote.cells_grand_summary <- function(loc, data, footnote) { - data + add_grand_summary_location_row( + loc = loc, + data = data, + text = footnote, + df_type = "footnotes_df" + ) } #' @importFrom dplyr bind_rows tibble distinct diff --git a/R/tab_options.R b/R/tab_options.R index 5dd2cc0c73..39e15ac117 100644 --- a/R/tab_options.R +++ b/R/tab_options.R @@ -19,11 +19,11 @@ #' units of pixels. The \code{\link{px}()} and \code{\link{pct}()} helper #' functions can also be used to pass in numeric values and obtain values as #' pixel or percent units. -#' @param column_labels.font.weight,row_group.font.weight the font weight of the -#' \code{columns} and \code{row_group} text element. -#' @param summary_row.text_transform an option to apply text transformations to -#' the label text in each summary row. -#' @param table.background.color,heading.background.color,column_labels.background.color,row_group.background.color,summary_row.background.color +#' @param column_labels.font.weight,row_group.font.weight the font weight of +#' the \code{columns} and \code{row_group} text element. +#' @param summary_row.text_transform,grand_summary_row.text_transform an option +#' to apply text transformations to the label text in each summary row. +#' @param table.background.color,heading.background.color,column_labels.background.color,row_group.background.color,summary_row.background.color,grand_summary_row.background.color #' background colors for the parent element \code{table} and the following #' child elements: \code{heading}, \code{columns}, \code{row_group}, #' \code{summary_row}, and \code{table_body}. A color name or a hexadecimal @@ -40,8 +40,8 @@ #' the style, width, and color of the table body's top border. #' @param table_body.border.bottom.style,table_body.border.bottom.width,table_body.border.bottom.color #' the style, width, and color of the table body's bottom border. -#' @param row.padding,summary_row.padding the amount of padding in each row and -#' in each summary row. +#' @param row.padding,summary_row.padding,grand_summary_row.padding the amount +#' of padding in each row and in each type of summary row. #' @param footnote.sep the separating characters between adjacent footnotes in #' the footnotes section. The default value produces a linebreak. #' @param footnote.glyph the set of sequential figures or characters used to @@ -190,6 +190,9 @@ tab_options <- function(data, summary_row.background.color = NULL, summary_row.padding = NULL, summary_row.text_transform = NULL, + grand_summary_row.background.color = NULL, + grand_summary_row.padding = NULL, + grand_summary_row.text_transform = NULL, footnote.sep = NULL, footnote.glyph = NULL, footnote.font.size = NULL, @@ -497,6 +500,30 @@ tab_options <- function(data, opts_df, "summary_row_text_transform", summary_row.text_transform) } + # grand_summary_row.background.color + if (!is.null(grand_summary_row.background.color)) { + + opts_df <- opts_df_set( + opts_df, "grand_summary_row_background_color", grand_summary_row.background.color) + } + + # grand_summary_row.padding + if (!is.null(grand_summary_row.padding)) { + + if (is.numeric(grand_summary_row.padding)) { + grand_summary_row.padding <- paste0(grand_summary_row.padding, "px") + } + + opts_df <- opts_df_set(opts_df, "grand_summary_row_padding", grand_summary_row.padding) + } + + # grand_summary_row.text_transform + if (!is.null(grand_summary_row.text_transform)) { + + opts_df <- opts_df_set( + opts_df, "grand_summary_row_text_transform", grand_summary_row.text_transform) + } + # footnote.sep if (!is.null(footnote.sep)) { diff --git a/R/tab_style.R b/R/tab_style.R index fba6e83efd..f73ecea785 100644 --- a/R/tab_style.R +++ b/R/tab_style.R @@ -233,21 +233,20 @@ set_style.cells_title <- function(loc, data, style) { set_style.cells_summary <- function(loc, data, style) { - groups <- (loc$groups %>% as.character())[-1] - rows <- (loc$rows %>% as.character())[-1] %>% as.integer() - - resolved <- resolve_cells_column_labels(data = data, object = loc) - - cols <- resolved$columns - - colnames <- colnames(as.data.frame(data))[cols] + add_summary_location_row( + loc = loc, + data = data, + text = style, + df_type = "styles_df" + ) +} - attr(data, "styles_df") <- - add_location_row( - data, df_type = "styles_df", - locname = "summary_cells", locnum = 5, - grpname = groups, colname = colnames, - rownum = rows, text = style) +set_style.cells_grand_summary <- function(loc, data, style) { - data + add_grand_summary_location_row( + loc = loc, + data = data, + text = style, + df_type = "styles_df" + ) } diff --git a/R/utils.R b/R/utils.R index 07c31f5c27..74c7178599 100644 --- a/R/utils.R +++ b/R/utils.R @@ -615,7 +615,15 @@ warn_on_scale_by_input <- function(scale_by) { #' @noRd derive_summary_label <- function(fn) { - if (inherits(fn, "formula")) { + if (is.function(fn)) { + + # Stop the function if any functions provided + # as bare names (e.g., `mean`) don't have + # names provided + stop("All functions provided as bare names in `fns` need a label.", + call. = FALSE) + + } else if (inherits(fn, "formula")) { (fn %>% rlang::f_rhs())[[1]] %>% as.character() @@ -821,6 +829,10 @@ tidy_gsub <- function(x, pattern, replacement, fixed = FALSE) { gsub(pattern, replacement, x, fixed = fixed) } +tidy_sub <- function(x, pattern, replacement, fixed = FALSE) { + + sub(pattern, replacement, x, fixed = fixed) +} #' An options setter for the `opts_df` data frame #' diff --git a/R/utils_formatters.R b/R/utils_formatters.R index 352ec85b03..8c5034e680 100644 --- a/R/utils_formatters.R +++ b/R/utils_formatters.R @@ -262,6 +262,40 @@ to_latex_math_mode <- function(x, } } +#' Obtain the contextually correct minus mark +#' +#' @param context The output context. +#' @noRd +context_missing_text <- function(missing_text, + context) { + + missing_text <- process_text(missing_text, context) + + switch(context, + html = + { + if (missing_text == "---") { + "—" + } else if (missing_text == "--") { + "–" + } else { + missing_text + } + }, + latex = missing_text, + { + if (missing_text == "---") { + "\u2014" + } else if (missing_text == "--") { + "\u2013" + } else { + missing_text + } + }) +} +context_dash_mark <- context_missing_text + + #' Obtain the contextually correct minus mark #' #' @param context The output context. diff --git a/R/utils_render_common.R b/R/utils_render_common.R index 8639041390..69a02f6d40 100644 --- a/R/utils_render_common.R +++ b/R/utils_render_common.R @@ -1,3 +1,6 @@ + +grand_summary_col <- "::GRAND_SUMMARY" + # Utility function to generate column numbers from column names; # used in: `resolve_footnotes_styles()` colname_to_colnum <- function(boxh_df, @@ -241,7 +244,8 @@ perform_col_merge <- function(col_merge, data_df, output_df, boxh_df, - columns_df) { + columns_df, + context) { if (length(col_merge) == 0) { return( @@ -254,7 +258,13 @@ perform_col_merge <- function(col_merge, for (i in seq(col_merge[[1]])) { - pattern <- col_merge[["pattern"]][i] + sep <- col_merge[["sep"]][i] %>% context_dash_mark(context = context) + + pattern <- + col_merge[["pattern"]][i] %>% + tidy_sub("\\{sep\\}", sep) + + value_1_col <- col_merge[["col_1"]][i] %>% unname() value_2_col <- col_merge[["col_1"]][i] %>% names() @@ -315,12 +325,18 @@ perform_col_merge <- function(col_merge, create_summary_dfs <- function(summary_list, data_df, stub_df, - output_df) { + output_df, + context) { + # If the `summary_list` object is an empty list, + # return an empty list as the `list_of_summaries` if (length(summary_list) == 0) { return(list()) } + # Create empty lists that are to contain summary + # data frames for display and for data collection + # purposes summary_df_display_list <- list() summary_df_data_list <- list() @@ -328,94 +344,127 @@ create_summary_dfs <- function(summary_list, summary_attrs <- summary_list[[i]] + groups <- summary_attrs$groups + columns <- summary_attrs$columns + fns <- summary_attrs$fns + missing_text <- summary_attrs$missing_text + formatter <- summary_attrs$formatter + formatter_options <- summary_attrs$formatter_options + labels <- summary_attrs$summary_labels + + if (length(labels) != length(unique(labels))) { + + stop("All summary labels must be unique:\n", + " * Review the names provided in `fns`\n", + " * These labels are in conflict: ", + paste0(labels, collapse = ", "), ".", + call. = FALSE) + } + # Resolve the `missing_text` - if (summary_attrs$missing_text == "---") { - summary_attrs$missing_text <- "\u2014" - } else if (missing_text == "--") { - summary_attrs$missing_text <- "\u2013" + missing_text <- + context_missing_text(missing_text = missing_text, context = context) + + assert_rowgroups <- function() { + + if (all(is.na(stub_df$groupname))) { + stop("There are no row groups in the gt object:\n", + " * Use `groups = NULL` to create a grand summary\n", + " * Define row groups using `gt()` or `tab_row_group()`", + call. = FALSE) + } } - # Resolve the groups to consider - if (isTRUE(summary_attrs$groups)) { + # Resolve the groups to consider; if + # `groups` is TRUE then we are to obtain + # summary row data for all groups + if (isTRUE(groups)) { + + assert_rowgroups() + groups <- unique(stub_df$groupname) - } else { - groups <- summary_attrs$groups - } - # Resolve the columns to exclude - if (isTRUE(summary_attrs$columns)) { - columns <- character(0) - } else { - columns <- base::setdiff(colnames(output_df), summary_attrs$columns) - } + } else if (!is.null(groups) && is.character(groups)) { - # Combine `groupname` with the table body data in order to - # process data by groups - groups_data_df <- - cbind( - stub_df[ - seq(nrow(stub_df)), - c("groupname", "rowname")], - data_df)[, -2] + assert_rowgroups() - # Get the registered function calls - agg_funs <- summary_attrs$fns %>% lapply(rlang::as_function) + # Get the names of row groups available + # in the gt object + groups_available <- unique(stub_df$groupname) + + if (any(!(groups %in% groups_available))) { + + # Stop function if one or more `groups` + # are not present in the gt table + stop("All `groups` should be available in the gt object:\n", + " * The following groups aren't present: ", + paste0( + base::setdiff(groups, groups_available), + collapse = ", " + ), "\n", + call. = FALSE) + } - # Get the names if any were provided - labels <- names(summary_attrs$fns) %>% process_text() + } else if (is.null(groups)) { - # If names weren't provided at all, handle this case by - # creating a vector of NAs that will be replaced later with - # derived names - if (length(labels) < 1) { - labels <- rep(NA_character_, length(summary_attrs$fns)) + # If groups is given as NULL (the default) + # then use a special group (`::GRAND_SUMMARY`) + groups <- grand_summary_col } - # If one or more names not provided then replace the empty - # string with NA - labels[labels == ""] <- NA_character_ + # Resolve the columns to exclude + columns_excl <- base::setdiff(colnames(output_df), columns) - # Get the labels for each of the function calls - derived_labels <- - summary_attrs$fns %>% - lapply(derive_summary_label) %>% - unlist() %>% - unname() %>% - make.names(unique = TRUE) + # Combine `groupname` with the table body data in order to + # process data by groups + if (identical(groups, grand_summary_col)) { - # Replace missing labels with derived labels - labels[is.na(labels)] <- derived_labels[is.na(labels)] + select_data_df <- + cbind( + stub_df[c("groupname", "rowname")], + data_df)[, -2] %>% + dplyr::mutate(groupname = grand_summary_col) %>% + dplyr::select(groupname, columns) - # Initialize an empty tibble to bind to - summary_dfs <- dplyr::tibble() + } else { - for (j in seq(agg_funs)) { + select_data_df <- + cbind( + stub_df[c("groupname", "rowname")], + data_df)[, -2] %>% + dplyr::select(groupname, columns) + } - # Get aggregation rows for each of the `agg_funs` - summary_dfs <- - dplyr::bind_rows( - summary_dfs, - groups_data_df %>% - dplyr::select(c("groupname", colnames(output_df))) %>% + # Get the registered function calls + agg_funs <- fns %>% lapply(rlang::as_closure) + + summary_dfs_data <- + lapply( + seq(agg_funs), function(j) { + select_data_df %>% dplyr::filter(groupname %in% groups) %>% dplyr::group_by(groupname) %>% dplyr::summarize_all(.funs = agg_funs[[j]]) %>% dplyr::ungroup() %>% dplyr::mutate(rowname = labels[j]) %>% - dplyr::select(groupname, rowname, dplyr::everything())) - } + dplyr::select(groupname, rowname, dplyr::everything()) + } + ) %>% + dplyr::bind_rows() + + # Add those columns that were not part of + # the aggregation, filling those with NA values + summary_dfs_data[, columns_excl] <- NA_real_ - # Exclude columns that are not requested by - # filling those with NA values summary_dfs_data <- - summary_dfs %>% - dplyr::mutate_at(.vars = columns, .funs = function(x) {NA_real_}) + summary_dfs_data %>% + dplyr::select(groupname, rowname, colnames(output_df)) # Format the displayed summary lines summary_dfs_display <- - summary_dfs %>% + summary_dfs_data %>% dplyr::mutate_at( - .vars = summary_attrs$columns, + .vars = columns, .funs = function(x) { format_data <- @@ -427,16 +476,12 @@ create_summary_dfs <- function(summary_list, summary_attrs$formatter_options)) formatter <- attr(format_data, "formats")[[1]]$func - - if ("html" %in% names(formatter)) { - formatter$html(x) - } else { - formatter$default(x) - } + fmt <- formatter[[context]] %||% formatter$default + fmt(x) } ) %>% dplyr::mutate_at( - .vars = columns, + .vars = columns_excl, .funs = function(x) {NA_character_}) for (group in groups) { @@ -462,14 +507,14 @@ create_summary_dfs <- function(summary_list, } } - # Condense data in summary_df_display_list in a + # Condense data in `summary_df_display_list` in a # groupwise manner summary_df_display_list <- tapply( summary_df_display_list, names(summary_df_display_list), - dplyr::bind_rows) - + dplyr::bind_rows + ) for (i in seq(summary_df_display_list)) { @@ -487,12 +532,16 @@ create_summary_dfs <- function(summary_list, summary_df_display_list[[i]] <- summary_df_display_list[[i]][ match(arrangement, summary_df_display_list[[i]]$rowname), ] %>% - replace(is.na(.), summary_attrs$missing_text) + replace(is.na(.), missing_text) } + # Return a list of lists, each of which have + # summary data frames for display and for data + # collection purposes list( summary_df_data_list = summary_df_data_list, - summary_df_display_list = summary_df_display_list) + summary_df_display_list = summary_df_display_list + ) } migrate_labels <- function(row_val) { @@ -730,11 +779,6 @@ create_summary_rows <- function(n_rows, body_content_summary <- as.vector(t(summary_df)) - if (context == "latex") { - body_content_summary <- body_content_summary %>% - tidy_gsub("\u2014", "---") - } - row_splits_summary <- split_body_content( body_content = body_content_summary, diff --git a/R/utils_render_footnotes.R b/R/utils_render_footnotes.R index a5b0cab978..210caae634 100644 --- a/R/utils_render_footnotes.R +++ b/R/utils_render_footnotes.R @@ -170,6 +170,31 @@ resolve_footnotes_styles <- function(output_df, ) } + # For the grand summary cells, insert a `colnum` based + # on `groups_rows_df` + if (6 %in% tbl[["locnum"]]) { + + tbl_not_g_summary_cells <- + tbl %>% + dplyr::filter(locnum != 6) + + tbl_g_summary_cells <- + tbl %>% + dplyr::filter(locnum == 6) %>% + dplyr::mutate( + colnum = colname_to_colnum( + boxh_df = boxh_df, colname = colname + ) + ) + + # Re-combine `tbl_not_g_summary_cells` + # with `tbl_g_summary_cells` + tbl <- + dplyr::bind_rows( + tbl_not_g_summary_cells, tbl_g_summary_cells + ) + } + # For the column label cells, insert a `colnum` # based on `boxh_df` if ("columns_columns" %in% tbl[["locname"]]) { @@ -536,37 +561,72 @@ apply_footnotes_to_summary <- function(list_of_summaries, summary_df_list <- list_of_summaries$summary_df_display_list - if (!("summary_cells" %in% footnotes_resolved$locname)) { + if (!("summary_cells" %in% footnotes_resolved$locname | + "grand_summary_cells" %in% footnotes_resolved$locname)) { return(list_of_summaries) } - footnotes_tbl_data <- - footnotes_resolved %>% - dplyr::filter(locname == "summary_cells") + if ("summary_cells" %in% footnotes_resolved$locname) { + + footnotes_tbl_data <- + footnotes_resolved %>% + dplyr::filter(locname == "summary_cells") - footnotes_data_glpyhs <- - footnotes_tbl_data %>% - dplyr::mutate(row = as.integer(round((rownum - floor(rownum)) * 100, 0))) %>% - dplyr::group_by(grpname, row, colnum) %>% - dplyr::mutate(fs_id_coalesced = paste(fs_id, collapse = ",")) %>% - dplyr::ungroup() %>% - dplyr::select(grpname, colname, row, fs_id_coalesced) %>% - dplyr::distinct() + footnotes_data_glpyhs <- + footnotes_tbl_data %>% + dplyr::mutate(row = as.integer(round((rownum - floor(rownum)) * 100, 0))) %>% + dplyr::group_by(grpname, row, colnum) %>% + dplyr::mutate(fs_id_coalesced = paste(fs_id, collapse = ",")) %>% + dplyr::ungroup() %>% + dplyr::select(grpname, colname, row, fs_id_coalesced) %>% + dplyr::distinct() - for (i in seq(nrow(footnotes_data_glpyhs))) { + for (i in seq(nrow(footnotes_data_glpyhs))) { - text <- - summary_df_list[[footnotes_data_glpyhs[i, ][["grpname"]]]][[ - footnotes_data_glpyhs$row[i], footnotes_data_glpyhs$colname[i]]] + text <- + summary_df_list[[footnotes_data_glpyhs[i, ][["grpname"]]]][[ + footnotes_data_glpyhs$row[i], footnotes_data_glpyhs$colname[i]]] + + text <- + paste0(text, footnote_glyph_to_html(footnotes_data_glpyhs$fs_id_coalesced[i])) - text <- - paste0(text, footnote_glyph_to_html(footnotes_data_glpyhs$fs_id_coalesced[i])) + summary_df_list[[footnotes_data_glpyhs[i, ][["grpname"]]]][[ + footnotes_data_glpyhs$row[i], footnotes_data_glpyhs$colname[i]]] <- text + } - summary_df_list[[footnotes_data_glpyhs[i, ][["grpname"]]]][[ - footnotes_data_glpyhs$row[i], footnotes_data_glpyhs$colname[i]]] <- text + list_of_summaries$summary_df_display_list <- summary_df_list } - list_of_summaries$summary_df_display_list <- summary_df_list + if ("grand_summary_cells" %in% footnotes_resolved$locname) { + + footnotes_tbl_data <- + footnotes_resolved %>% + dplyr::filter(locname == "grand_summary_cells") + + footnotes_data_glpyhs <- + footnotes_tbl_data %>% + dplyr::group_by(rownum, colnum) %>% + dplyr::mutate(fs_id_coalesced = paste(fs_id, collapse = ",")) %>% + dplyr::ungroup() %>% + dplyr::select(colname, rownum, fs_id_coalesced) %>% + dplyr::distinct() + + for (i in seq(nrow(footnotes_data_glpyhs))) { + + text <- + summary_df_list[[grand_summary_col]][[ + footnotes_data_glpyhs$rownum[i], footnotes_data_glpyhs$colname[i]]] + + text <- + paste0(text, footnote_glyph_to_html(footnotes_data_glpyhs$fs_id_coalesced[i])) + + summary_df_list[[grand_summary_col]][[ + footnotes_data_glpyhs$rownum[i], footnotes_data_glpyhs$colname[i]]] <- text + } + + list_of_summaries$summary_df_display_list[[grand_summary_col]] <- + summary_df_list[[grand_summary_col]] + } list_of_summaries } diff --git a/R/utils_render_html.R b/R/utils_render_html.R index da9453fa07..f3314ce51a 100644 --- a/R/utils_render_html.R +++ b/R/utils_render_html.R @@ -139,10 +139,9 @@ apply_styles_to_summary_output <- function(summary_df, styles_summary_df <- summary_df styles_summary_df[] <- NA_character_ - styles_tbl_summary <- styles_resolved %>% - dplyr::filter(locname == "summary_cells") %>% + dplyr::filter(locname %in% "summary_cells") %>% dplyr::filter(grpname == group) if (nrow(styles_tbl_summary) > 0) { @@ -173,10 +172,49 @@ apply_styles_to_summary_output <- function(summary_df, split_body_content(body_content = summary_styles, n_cols) } -#' Create the opening HTML element of a table -#' +#' Apply styles to summary rows +#' @importFrom dplyr filter group_by mutate ungroup select distinct #' @noRd -create_table_start_h <- function() { +apply_styles_to_grand_summary_output <- function(summary_df, + styles_resolved, + n_cols) { + + styles_summary_df <- summary_df + styles_summary_df[] <- NA_character_ + + styles_tbl_summary <- + styles_resolved %>% + dplyr::filter(locname %in% "grand_summary_cells") + + if (nrow(styles_tbl_summary) > 0) { + + styles_summary <- + styles_tbl_summary %>% + dplyr::group_by(colname, rownum) %>% + dplyr::mutate(styles_appended = paste(text, collapse = "")) %>% + dplyr::ungroup() %>% + dplyr::select(colname, rownum, styles_appended) %>% + dplyr::distinct() + + + for (i in seq(nrow(styles_summary))) { + + styles_summary_df[ + styles_summary$rownum[i], styles_summary$colname[i]] <- + styles_summary$styles_appended[i] + } + } + + # Extract `summary_styles` as a vector + summary_styles <- as.vector(t(styles_summary_df)) + + # Split `summary_styles` by slices of rows + split_body_content(body_content = summary_styles, n_cols) +} + +# Create the opening HTML element of a table +create_table_start_h <- function(groups_rows_df) { + "\n\n" } @@ -782,6 +820,62 @@ create_body_component_h <- function(row_splits_body, } } + # If there is a grand summary, include that at the end + if (summaries_present && + grand_summary_col %in% names(list_of_summaries$summary_df_display_list)) { + + grand_summary_df <- + list_of_summaries$summary_df_display_list[[grand_summary_col]] %>% + as.data.frame(stringsAsFactors = FALSE) + + row_splits_summary_styles <- + apply_styles_to_grand_summary_output( + summary_df = grand_summary_df, + styles_resolved = styles_resolved, + n_cols = n_cols + ) + + grand_summary <- as.vector(t(grand_summary_df)) + + row_splits_grand_summary <- + split_body_content( + body_content = grand_summary, + n_cols = n_cols) + + # Provide CSS classes for leading and + # non-leading grand summary rows + gs_row_classes_first <- "gt_grand_summary_row gt_first_grand_summary_row " + gs_row_classes <- "gt_grand_summary_row " + + grand_summary_row_lines <- c() + + for (j in seq(length(row_splits_grand_summary))) { + + grand_summary_row_lines <- + c(grand_summary_row_lines, + paste0( + "\n", + paste0( + ""), "\n", + paste0( + "", collapse = "\n"), + "\n\n") + ) + } + + body_rows <- c(body_rows, grand_summary_row_lines) + } + # Create a single-length vector by collapsing all vector components body_rows <- body_rows %>% paste(collapse = "") diff --git a/inst/css/gt_colors.scss b/inst/css/gt_colors.scss index ed930fb169..e6277ebdf2 100644 --- a/inst/css/gt_colors.scss +++ b/inst/css/gt_colors.scss @@ -3,6 +3,7 @@ $heading_background_color: $table_background_color !default; $column_labels_background_color: $table_background_color !default; $row_group_background_color: $table_background_color !default; $summary_row_background_color: $table_background_color !default; +$grand_summary_row_background_color: $table_background_color !default; @function font-color($color) { @return if( diff --git a/inst/css/gt_styles_default.scss b/inst/css/gt_styles_default.scss index be32ebfb01..5da6844ce8 100644 --- a/inst/css/gt_styles_default.scss +++ b/inst/css/gt_styles_default.scss @@ -118,23 +118,34 @@ border-right-width: 2px; border-right-color: #A8A8A8; padding-left: 12px; - &.gt_row { - background-color: $table_background_color; - } } .gt_summary_row { + color: font-color($summary_row_background_color); background-color: $summary_row_background_color; /* summary_row.background.color */ padding: $summary_row_padding; /* summary_row.padding */ text-transform: $summary_row_text_transform; /* summary_row.text_transform */ } + .gt_grand_summary_row { + color: font-color($grand_summary_row_background_color); + background-color: $grand_summary_row_background_color; /* grand_summary_row.background.color */ + padding: $grand_summary_row_padding; /* grand_summary_row.padding */ + text-transform: $grand_summary_row_text_transform; /* grand_summary_row.text_transform */ + } + .gt_first_summary_row { border-top-style: solid; border-top-width: 2px; border-top-color: #A8A8A8; } + .gt_first_grand_summary_row { + border-top-style: double; + border-top-width: 6px; + border-top-color: #A8A8A8; + } + .gt_table_body { border-top-style: $table_body_border_top_style; /* table_body.border.top.style */ border-top-width: $table_body_border_top_width; /* table_body.border.top.width */ diff --git a/man/location_cells.Rd b/man/location_cells.Rd index bb6d154a7e..fec9154807 100644 --- a/man/location_cells.Rd +++ b/man/location_cells.Rd @@ -8,6 +8,7 @@ \alias{cells_stub} \alias{cells_data} \alias{cells_summary} +\alias{cells_grand_summary} \title{Helpers for targeting multiple cells in different locations} \usage{ cells_title(groups = c("title", "subtitle")) @@ -21,6 +22,8 @@ cells_stub(rows = NULL) cells_data(columns = NULL, rows = NULL) cells_summary(groups = NULL, columns = NULL, rows = NULL) + +cells_grand_summary(columns = NULL, rows = NULL) } \arguments{ \item{columns, rows, groups}{either a vector of names, a vector of diff --git a/man/summary_rows.Rd b/man/summary_rows.Rd index 61d9b09870..2ce924814c 100644 --- a/man/summary_rows.Rd +++ b/man/summary_rows.Rd @@ -4,54 +4,64 @@ \alias{summary_rows} \title{Add summary rows using aggregation functions} \usage{ -summary_rows(data, groups = NULL, columns = NULL, fns, +summary_rows(data, groups = NULL, columns = TRUE, fns, missing_text = "---", formatter = fmt_number, ...) } \arguments{ -\item{data}{a table object that is created using the \code{gt()} function.} +\item{data}{A table object that is created using the \code{gt()} function.} -\item{groups}{the row groups labels that identify which summary rows will be -added.} +\item{groups}{The groups to consider for generation of groupwise summary +rows. By default this is set to \code{NULL}, which results in the formation +of grand summary rows (a grand summary operates on all table data). +Providing the names of row groups in \code{c()} will create a groupwise +summary and generate summary rows for the specified groups. Setting this to +\code{TRUE} indicates that all available groups will receive groupwise +summary rows.} -\item{columns}{the columns for which the summaries should be calculated. If -nothing is provided, then the supplied aggregation functions will be -applied to all columns.} +\item{columns}{The columns for which the summaries should be calculated.} -\item{fns}{functions used for aggregations. This can include base functions +\item{fns}{Functions used for aggregations. This can include base functions like \code{mean}, \code{min}, \code{max}, \code{median}, \code{sd}, or \code{sum} or any other user-defined aggregation function. The function(s) should be supplied within a \code{list()}. Within that list, we can specify -the functions by use of function names (e.g., \code{"sum"}), the functions -themselves (e.g., \code{sum}), or one-sided R formulas by prefacing with a -\code{~} where \code{.} serves as the data to be summarized (e.g., -\code{sum(., na.rm = TRUE)}). By using named arguments, the names will -serve as row labels for the corresponding summary rows (otherwise the -labels will be derived from the function names).} +the functions by use of function names in quotes (e.g., \code{"sum"}), as +bare functions (e.g., \code{sum}), or as one-sided R formulas using a +leading \code{~}. In the formula representation, a \code{.} serves as the +data to be summarized (e.g., \code{sum(., na.rm = TRUE)}). The use of named +arguments is recommended as the names will serve as summary row labels for +the corresponding summary rows data (the labels can derived from the +function names but only when not providing bare function names).} -\item{missing_text}{the text to be used in place of \code{NA} values in +\item{missing_text}{The text to be used in place of \code{NA} values in summary cells with no data outputs.} -\item{formatter}{a formatter function name. These can be any of the +\item{formatter}{A formatter function name. These can be any of the \code{fmt_*()}functions available in the package (e.g., \code{\link{fmt_number}()}, \code{link{fmt_percent}()}, etc.), or a custom function using \code{\link{fmt}()}. The default function is \code{\link{fmt_number}()} and its options can be accessed through \code{...}.} -\item{...}{values passed to the \code{formatter} function, where the provided +\item{...}{Values passed to the \code{formatter} function, where the provided values are to be in the form of named vectors. For example, when using the default \code{formatter} function, \code{\link{fmt_number}()}, options such as \code{decimals}, \code{use_seps}, and \code{locale} can be used.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ -Add summary rows to one or more row groups by using the input data already -provided in the \code{\link{gt}()} function alongside any suitable -aggregation functions. Should we need to obtain the summary data for external -purposes, the \code{\link{extract_summary}()} can be used with a -\code{gt_tbl} object where summary rows were added via \code{summary_rows()}. +Add groupwise summary rows to one or more row groups by using the input data +already provided in the \code{\link{gt}()} function alongside any suitable +aggregation functions. Or, add a grand summary that incorporates all +available data, regardless of grouping. You choose how to format the values +in the resulting summary cells by use of a \code{formatter} function (e.g, +\code{\link{fmt_number}()}) and any relevant options. +} +\details{ +Should we need to obtain the summary data for external purposes, the +\code{\link{extract_summary}()} function can be used with a \code{gt_tbl} +object where summary rows were added via \code{summary_rows()}. } \section{Figures}{ diff --git a/man/tab_options.Rd b/man/tab_options.Rd index d7e22f59ec..e0ea146906 100644 --- a/man/tab_options.Rd +++ b/man/tab_options.Rd @@ -28,7 +28,10 @@ tab_options(data, table.width = NULL, table.font.size = NULL, table_body.border.bottom.width = NULL, table_body.border.bottom.color = NULL, row.padding = NULL, summary_row.background.color = NULL, summary_row.padding = NULL, - summary_row.text_transform = NULL, footnote.sep = NULL, + summary_row.text_transform = NULL, + grand_summary_row.background.color = NULL, + grand_summary_row.padding = NULL, + grand_summary_row.text_transform = NULL, footnote.sep = NULL, footnote.glyph = NULL, footnote.font.size = NULL, footnote.padding = NULL, sourcenote.font.size = NULL, sourcenote.padding = NULL, row.striping.include_stub = NULL, @@ -55,7 +58,7 @@ units of pixels. The \code{\link{px}()} and \code{\link{pct}()} helper functions can also be used to pass in numeric values and obtain values as pixel or percent units.} -\item{table.background.color, heading.background.color, column_labels.background.color, row_group.background.color, summary_row.background.color}{background colors for the parent element \code{table} and the following +\item{table.background.color, heading.background.color, column_labels.background.color, row_group.background.color, summary_row.background.color, grand_summary_row.background.color}{background colors for the parent element \code{table} and the following child elements: \code{heading}, \code{columns}, \code{row_group}, \code{summary_row}, and \code{table_body}. A color name or a hexadecimal color code should be provided.} @@ -64,8 +67,8 @@ color code should be provided.} \item{heading.border.bottom.style, heading.border.bottom.width, heading.border.bottom.color}{the style, width, and color of the heading's bottom border.} -\item{column_labels.font.weight, row_group.font.weight}{the font weight of the -\code{columns} and \code{row_group} text element.} +\item{column_labels.font.weight, row_group.font.weight}{the font weight of +the \code{columns} and \code{row_group} text element.} \item{column_labels.hidden}{an option to hide the column labels.} @@ -77,11 +80,11 @@ color code should be provided.} \item{table_body.border.bottom.style, table_body.border.bottom.width, table_body.border.bottom.color}{the style, width, and color of the table body's bottom border.} -\item{row.padding, summary_row.padding}{the amount of padding in each row and -in each summary row.} +\item{row.padding, summary_row.padding, grand_summary_row.padding}{the amount +of padding in each row and in each type of summary row.} -\item{summary_row.text_transform}{an option to apply text transformations to -the label text in each summary row.} +\item{summary_row.text_transform, grand_summary_row.text_transform}{an option +to apply text transformations to the label text in each summary row.} \item{footnote.sep}{the separating characters between adjacent footnotes in the footnotes section. The default value produces a linebreak.} diff --git a/tests/testthat/test-cols_merge.R b/tests/testthat/test-cols_merge.R index ac1c724510..96a928e71a 100644 --- a/tests/testthat/test-cols_merge.R +++ b/tests/testthat/test-cols_merge.R @@ -203,7 +203,7 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect that merging statements are stored in `col_merge` attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% - expect_equal("{1} — {2}") + expect_equal("{1} {sep} {2}") attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% @@ -223,7 +223,7 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect that merging statements are stored in `col_merge` attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% - expect_equal("{1} — {2}") + expect_equal("{1} {sep} {2}") attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% @@ -246,7 +246,10 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect that merging statements are stored in `col_merge` attr(tbl_html, "col_merge", exact = TRUE)$pattern[[1]] %>% - expect_equal("{1} — {2}") + expect_equal("{1} {sep} {2}") + + attr(tbl_html, "col_merge", exact = TRUE)$sep[[1]] %>% + expect_equal("---") attr(tbl_html, "col_merge", exact = TRUE)$col_1[1] %>% names() %>% @@ -257,7 +260,10 @@ test_that("the `cols_merge_range()` function works correctly", { expect_equal("col_1") attr(tbl_html, "col_merge", exact = TRUE)$pattern[[2]] %>% - expect_equal("{1} — {2}") + expect_equal("{1} {sep} {2}") + + attr(tbl_html, "col_merge", exact = TRUE)$sep[[2]] %>% + expect_equal("---") attr(tbl_html, "col_merge", exact = TRUE)$col_1[2] %>% names() %>% diff --git a/tests/testthat/test-conditional_fmt.R b/tests/testthat/test-conditional_fmt.R index fb865d5731..89b95c4e31 100644 --- a/tests/testthat/test-conditional_fmt.R +++ b/tests/testthat/test-conditional_fmt.R @@ -234,7 +234,7 @@ test_that("the `fmt_missing()` function works with conditional `rows`", { columns = vars(num_2), rows = num_1 <= 0) %>% render_formats_test(context = "html"))[["num_2"]], - c("34", "74", "23", "NA", "35", rep("—", 2)) + c("34", "74", "23", "NA", "35", rep("—", 2)) ) }) diff --git a/tests/testthat/test-fmt_missing.R b/tests/testthat/test-fmt_missing.R index 004665734d..9108374732 100644 --- a/tests/testthat/test-fmt_missing.R +++ b/tests/testthat/test-fmt_missing.R @@ -54,13 +54,13 @@ test_that("the `fmt_missing()` function works correctly", { (tab %>% fmt_missing(columns = "num_1") %>% render_formats_test(context = "html"))[["num_1"]], - c("—", "74", "—", "93", "—", "76", "—")) + c("—", "74", "—", "93", "—", "76", "—")) expect_equal( (tab %>% fmt_missing(columns = "num_1", missing_text = "--") %>% render_formats_test(context = "html"))[["num_1"]], - c("–", "74", "–", "93", "–", "76", "–")) + c("–", "74", "–", "93", "–", "76", "–")) expect_equal( (tab %>% @@ -84,7 +84,7 @@ test_that("the `fmt_missing()` function works correctly", { (tab %>% fmt_missing(columns = "num_1", rows = num_2 < 50) %>% render_formats_test(context = "html"))[["num_1"]], - c("—", "74", "—", "93", "—", "76", "NA")) + c("—", "74", "—", "93", "—", "76", "NA")) # Format columns with `fmt_number()` then use # `fmt_missing()` on all columns (the two functions @@ -97,7 +97,7 @@ test_that("the `fmt_missing()` function works correctly", { ) %>% fmt_missing(columns = TRUE) %>% render_formats_test(context = "html"))[["num_1"]], - c("—", "74.000", "—", "93.000", "—", "76.000", "—")) + c("—", "74.000", "—", "93.000", "—", "76.000", "—")) # Reverse the ordering: use `fmt_missing()` first # then `fmt_number()`; expect the same output as before @@ -109,5 +109,5 @@ test_that("the `fmt_missing()` function works correctly", { decimals = 3 ) %>% render_formats_test(context = "html"))[["num_1"]], - c("—", "74.000", "—", "93.000", "—", "76.000", "—")) + c("—", "74.000", "—", "93.000", "—", "76.000", "—")) }) diff --git a/tests/testthat/test-l_cols_merge.R b/tests/testthat/test-l_cols_merge.R index 6ad98ee5d6..3ba26209b6 100644 --- a/tests/testthat/test-l_cols_merge.R +++ b/tests/testthat/test-l_cols_merge.R @@ -182,16 +182,16 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect a characteristic pattern grepl( paste0( - ".*767.6 — 928.1 & 382.0 & 674.5", - ".*403.3 — 461.5 & 15.1 & 242.8", - ".*686.4 — 54.1 & 282.7 & 56.3", - ".*662.6 — 148.8 & 984.6 & 928.1", - ".*198.5 — 65.1 & 127.4 & 219.3", - ".*132.1 — 118.1 & 91.2 & 874.3", - ".*349.7 — 307.1 & 566.7 & 542.9", - ".*63.7 — 504.3 & 152.0 & 724.5", - ".*105.4 — 729.8 & 962.4 & 336.4", - ".*924.2 — 424.6 & 740.8 & 104.2.*"), + ".*767.6 --- 928.1 & 382.0 & 674.5", + ".*403.3 --- 461.5 & 15.1 & 242.8", + ".*686.4 --- 54.1 & 282.7 & 56.3", + ".*662.6 --- 148.8 & 984.6 & 928.1", + ".*198.5 --- 65.1 & 127.4 & 219.3", + ".*132.1 --- 118.1 & 91.2 & 874.3", + ".*349.7 --- 307.1 & 566.7 & 542.9", + ".*63.7 --- 504.3 & 152.0 & 724.5", + ".*105.4 --- 729.8 & 962.4 & 336.4", + ".*924.2 --- 424.6 & 740.8 & 104.2.*"), tbl_latex %>% as_latex() %>% as.character()) %>% expect_true() @@ -207,16 +207,16 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect a characteristic pattern grepl( paste0( - ".*767.6 — 928.1 & 382.0 & 674.5", - ".*403.3 — 461.5 & 15.1 & 242.8", - ".*686.4 — 54.1 & 282.7 & 56.3", - ".*662.6 — 148.8 & 984.6 & 928.1", - ".*198.5 — 65.1 & 127.4 & 219.3", - ".*132.1 — 118.1 & 91.2 & 874.3", - ".*349.7 — 307.1 & 566.7 & 542.9", - ".*63.7 — 504.3 & 152.0 & 724.5", - ".*105.4 — 729.8 & 962.4 & 336.4", - ".*924.2 — 424.6 & 740.8 & 104.2.*"), + ".*767.6 --- 928.1 & 382.0 & 674.5", + ".*403.3 --- 461.5 & 15.1 & 242.8", + ".*686.4 --- 54.1 & 282.7 & 56.3", + ".*662.6 --- 148.8 & 984.6 & 928.1", + ".*198.5 --- 65.1 & 127.4 & 219.3", + ".*132.1 --- 118.1 & 91.2 & 874.3", + ".*349.7 --- 307.1 & 566.7 & 542.9", + ".*63.7 --- 504.3 & 152.0 & 724.5", + ".*105.4 --- 729.8 & 962.4 & 336.4", + ".*924.2 --- 424.6 & 740.8 & 104.2.*"), tbl_latex %>% as_latex() %>% as.character()) %>% expect_true() @@ -235,16 +235,16 @@ test_that("the `cols_merge_range()` function works correctly", { # Expect a characteristic pattern grepl( paste0( - ".*767.6 — 928.1 & 382.0 — 674.5", - ".*403.3 — 461.5 & 15.1 — 242.8", - ".*686.4 — 54.1 & 282.7 — 56.3", - ".*662.6 — 148.8 & 984.6 — 928.1", - ".*198.5 — 65.1 & 127.4 — 219.3", - ".*132.1 — 118.1 & 91.2 — 874.3", - ".*349.7 — 307.1 & 566.7 — 542.9", - ".*63.7 — 504.3 & 152.0 — 724.5", - ".*105.4 — 729.8 & 962.4 — 336.4", - ".*924.2 — 424.6 & 740.8 — 104.2.*"), + ".*767.6 --- 928.1 & 382.0 --- 674.5", + ".*403.3 --- 461.5 & 15.1 --- 242.8", + ".*686.4 --- 54.1 & 282.7 --- 56.3", + ".*662.6 --- 148.8 & 984.6 --- 928.1", + ".*198.5 --- 65.1 & 127.4 --- 219.3", + ".*132.1 --- 118.1 & 91.2 --- 874.3", + ".*349.7 --- 307.1 & 566.7 --- 542.9", + ".*63.7 --- 504.3 & 152.0 --- 724.5", + ".*105.4 --- 729.8 & 962.4 --- 336.4", + ".*924.2 --- 424.6 & 740.8 --- 104.2.*"), tbl_latex %>% as_latex() %>% as.character()) %>% expect_true() diff --git a/tests/testthat/test-location_cells.R b/tests/testthat/test-location_cells.R index d8aedc2717..1643a359f6 100644 --- a/tests/testthat/test-location_cells.R +++ b/tests/testthat/test-location_cells.R @@ -238,7 +238,8 @@ test_that("the `cells_summary()` function works correctly", { helper_cells_summary <- cells_summary( groups = "group_a", - columns = c("col_1", "col_2")) + columns = c("col_1", "col_2") + ) # Expect this has the `cells_summary` and `location_cells` classes helper_cells_summary %>% @@ -274,7 +275,67 @@ test_that("the `cells_summary()` function works correctly", { helper_cells_summary[[2]][2] %>% as.character() %>% expect_equal("c(\"col_1\", \"col_2\")") + + # Create a `cells_summary` object with + # columns in `vars()` provided to `columns` + helper_cells_summary <- + cells_summary( + groups = "group_a", + columns = vars(col_1, col_2) + ) + + # Expect the RHS of the second component formula to contain + # the vector provided + helper_cells_summary[[2]][2] %>% + as.character() %>% + expect_equal("vars(col_1, col_2)") }) +test_that("the `cells_grand_summary()` function works correctly", { + + # Create a `cells_grand_summary` object with names provided to `columns` + helper_cells_grand_summary <- + cells_grand_summary( + columns = c("col_1", "col_2") + ) + + # Expect this has the `cells_summary` and `location_cells` classes + helper_cells_grand_summary %>% + expect_is(c("cells_grand_summary", "location_cells")) + + # Expect the length of the object to be `2` + helper_cells_grand_summary %>% + length() %>% + expect_equal(2) + + # Expect that the object has the names `columns` and `rows` + helper_cells_grand_summary %>% + names() %>% + expect_equal(c("columns", "rows")) + + # Expect the first list component to have the `quosure` and `formula` classes + helper_cells_grand_summary[[1]] %>% expect_is(c("quosure", "formula")) + # Expect the second list component to have the `quosure` and `formula` classes + helper_cells_grand_summary[[2]] %>% expect_is(c("quosure", "formula")) + + # Expect the RHS of the first component formula to contain + # the vector provided + helper_cells_grand_summary[[1]][2] %>% + as.character() %>% + expect_equal("c(\"col_1\", \"col_2\")") + + # Create a `cells_grand_summary` object with + # columns in `vars()` provided to `columns` + helper_cells_grand_summary <- + cells_grand_summary( + columns = vars(col_1, col_2) + ) + + # Expect the RHS of the first component formula to contain + # the vector provided + helper_cells_grand_summary[[1]][2] %>% + as.character() %>% + expect_equal("vars(col_1, col_2)") +}) diff --git a/tests/testthat/test-summary_rows.R b/tests/testthat/test-summary_rows.R index 4a6a66d2f9..453c8d19cd 100644 --- a/tests/testthat/test-summary_rows.R +++ b/tests/testthat/test-summary_rows.R @@ -1,30 +1,37 @@ context("Ensuring that the `summary_rows()` function works as expected") -# Create a table with group names, rownames, and two columns of values +# Create a table based on `sp500`, with +# group names, rownames, and four +# columns of values tbl <- - dplyr::tribble( - ~groupname, ~rowname, ~value_1, ~value_2, - "A", "1", NA, 260.1, - "A", "2", 184.3, 84.4, - "A", "3", 342.3, 126.3, - "A", "4", 234.9, NA, - "B", "1", 190.9, 832.5, - "B", "2", 743.3, 281.2, - "B", "3", 252.3, 732.5, - "B", "4", 344.7, NA, - "C", "1", 197.2, 818.0, - "C", "2", 284.3, 394.4) - -test_that("the `summary_rows()` function works correctly", { - - # Create a table with summary rows for the `A` and `C` groups; - # the 3 summary rows for these groups represent the mean, sum, - # and standard deviation of `value` + sp500 %>% + dplyr::filter( + date >= "2015-01-05" & + date <="2015-01-16" + ) %>% + dplyr::arrange(date) %>% + dplyr::mutate( + week = paste0( + "W", strftime(date, format = "%V")) + ) %>% + dplyr::select(-adj_close, -volume) %>% + gt( + rowname_col = "date", + groupname_col = "week" + ) + +test_that("the `summary_rows()` can make groupwise summaries", { + + # Create a table with summary rows for + # the `W02` group; the 3 summary rows for + # this group represent the mean, sum, + # and standard deviation of all numeric + # columns gt_tbl <- - gt(tbl) %>% + tbl %>% summary_rows( - groups = c("A", "C"), - columns = vars(value_1), + groups = "W02", + columns = vars(open, high, low, close), fns = list( average = ~mean(., na.rm = TRUE), total = ~sum(., na.rm = TRUE), @@ -33,8 +40,9 @@ test_that("the `summary_rows()` function works correctly", { # Extract the internal `summary` object summary <- attr(gt_tbl, "summary", exact = TRUE) - # Expect that the internal `summary` list object has - # a length of `1` since there was only one call of `summary_rows()` + # Expect that the internal `summary` list + # object has a length of `1` since there was + # only one call of `summary_rows()` length(summary) %>% expect_equal(1) @@ -43,22 +51,23 @@ test_that("the `summary_rows()` function works correctly", { summary[[1]] %>% names() %>% expect_equal( - c("groups", "columns", "fns", "missing_text", - "formatter", "formatter_options")) + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) # Expect the `groups` provided in `summary[[1]]$groups` summary[[1]]$groups %>% - expect_equal(c("A", "C")) + expect_equal("W02") # Expect the `columns` provided in `summary[[1]]$columns` summary[[1]]$columns %>% - expect_equal("value_1") + expect_equal(c("open", "high", "low", "close")) - # Expect that `summary[[1]]$fns` is a `fun_list` object + # Expect that `summary[[1]]$fns` is a `list` object summary[[1]]$fns %>% expect_is("list") - # Expect that the components of `summary[[1]]$fns` are quosures + # Expect that the components of `summary[[1]]$fns` are formulas summary[[1]]$fns$average %>% expect_is("formula") summary[[1]]$fns$total %>% expect_is("formula") summary[[1]]$fns$`std dev` %>% expect_is("formula") @@ -75,13 +84,22 @@ test_that("the `summary_rows()` function works correctly", { summary[[1]]$formatter_options %>% expect_is("list") - # Create a table with summary rows for all groups and for `value_1`; - # the 3 summary rows for these groups represent the mean, sum, - # and the standard deviation + # Expect that `summary[[1]]$formatter_options` is + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + # Create a table with summary rows for + # the `W02` group; the 3 summary rows for + # this group represent the mean, sum, + # and standard deviation of only the + # `open` column gt_tbl <- - gt(tbl) %>% + tbl %>% summary_rows( - columns = vars(value_1), + groups = "W02", + columns = vars(open), fns = list( average = ~mean(., na.rm = TRUE), total = ~sum(., na.rm = TRUE), @@ -90,32 +108,127 @@ test_that("the `summary_rows()` function works correctly", { # Extract the internal `summary` object summary <- attr(gt_tbl, "summary", exact = TRUE) - # Expect that the internal `summary` list object has - # a length of `1` since there was only one call of `summary_rows()` - length(summary) %>% - expect_equal(1) + # Expect the `groups` provided in `summary[[1]]$groups` + summary[[1]]$groups %>% + expect_equal("W02") - # For the single list component in `summary`, expect specific - # names within it - summary[[1]] %>% - names() %>% - expect_equal( - c("groups", "columns", "fns", "missing_text", - "formatter", "formatter_options")) + # Expect the `columns` provided in `summary[[1]]$columns` + summary[[1]]$columns %>% + expect_equal("open") - # Expect that `summary[[1]]$groups` is TRUE + # Expect that `summary[[1]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") + + # Expect that the components of `summary[[1]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + # Expect that `summary[[1]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + # Expect that `summary[[1]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + # Expect that `summary[[1]]$formatter_options` is + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + # Create a table with summary rows for + # the `W02` and `W03` groups; the 3 summary + # rows for these groups represent the mean, + # sum, and standard deviation of only the + # `open` column + gt_tbl <- + tbl %>% + summary_rows( + groups = c("W02", "W03"), + columns = vars(open), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE))) + + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect the `groups` provided in `summary[[1]]$groups` + summary[[1]]$groups %>% + expect_equal(c("W02", "W03")) + + # Expect the `columns` provided in `summary[[1]]$columns` + summary[[1]]$columns %>% + expect_equal("open") + + # Expect that `summary[[1]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") + + # Expect that the components of `summary[[1]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + # Expect that `summary[[1]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + # Expect that `summary[[1]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + # Expect that `summary[[1]]$formatter_options` is + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + # Create a table with summary rows for + # the `W02` and `W03` groups (using + # `groups = TRUE`); the 3 summary rows for + # these groups represent the mean, + # sum, and standard deviation of only the + # `open` column + gt_tbl <- + tbl %>% + summary_rows( + groups = TRUE, + columns = vars(open), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE))) + + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect the `groups` provided in `summary[[1]]$groups` + # to be `TRUE` summary[[1]]$groups %>% expect_true() - # Expect that `summary[[1]]$columns` is `value_1` + # Expect the `columns` provided in `summary[[1]]$columns` summary[[1]]$columns %>% - expect_equal("value_1") + expect_equal("open") - # Expect that `summary[[1]]$fns` is a `fun_list` object + # Expect that `summary[[1]]$fns` is a `list` object summary[[1]]$fns %>% expect_is("list") - # Expect that the components of `summary[[1]]$fns` are quosures + # Expect that the components of `summary[[1]]$fns` are formulas summary[[1]]$fns$average %>% expect_is("formula") summary[[1]]$fns$total %>% expect_is("formula") summary[[1]]$fns$`std dev` %>% expect_is("formula") @@ -132,26 +245,39 @@ test_that("the `summary_rows()` function works correctly", { summary[[1]]$formatter_options %>% expect_is("list") + # Expect that `summary[[1]]$formatter_options` is + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + # Create a table with two sets of summary rows for all groups # and all columns gt_tbl <- - gt(tbl) %>% + tbl %>% summary_rows( - columns = vars(value_1, value_2), + groups = TRUE, + columns = vars(open, high, low, close), fns = list( average = ~mean(., na.rm = TRUE), total = ~sum(., na.rm = TRUE), - `std dev` = ~sd(., na.rm = TRUE))) %>% + `std dev` = ~sd(., na.rm = TRUE) + ) + ) %>% summary_rows( - columns = vars(value_1, value_2), + groups = TRUE, + columns = vars(open, high, low, close), fns = list( - max = ~max(., na.rm = TRUE))) + max = ~max(., na.rm = TRUE) + ) + ) # Extract the internal `summary` object summary <- attr(gt_tbl, "summary", exact = TRUE) - # Expect that the internal `summary` list object has - # a length of `2 since there are two calls of `summary_rows()` + # Expect that the internal `summary` list + # object has a length of `2` since there + # were two calls of `summary_rows()` length(summary) %>% expect_equal(2) @@ -160,14 +286,16 @@ test_that("the `summary_rows()` function works correctly", { summary[[1]] %>% names() %>% expect_equal( - c("groups", "columns", "fns", "missing_text", - "formatter", "formatter_options")) + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) summary[[2]] %>% names() %>% expect_equal( - c("groups", "columns", "fns", "missing_text", - "formatter", "formatter_options")) + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) # Expect that `summary[[1|2]]$groups` is TRUE summary[[1]]$groups %>% @@ -178,19 +306,19 @@ test_that("the `summary_rows()` function works correctly", { # Expect that `summary[[1|2]]$columns` has specific values summary[[1]]$columns %>% - expect_equal(c("value_1", "value_2")) + expect_equal(c("open", "high", "low", "close")) summary[[2]]$columns %>% - expect_equal(c("value_1", "value_2")) + expect_equal(c("open", "high", "low", "close")) - # Expect that `summary[[1|2]]$fns` is a `fun_list` object + # Expect that `summary[[1|2]]$fns` is a `list` object summary[[1]]$fns %>% expect_is("list") summary[[2]]$fns %>% expect_is("list") - # Expect that the components of `summary[[1|2]]$fns` are quosures + # Expect that the components of `summary[[1|2]]$fns` are formulas summary[[1]]$fns$average %>% expect_is("formula") summary[[1]]$fns$total %>% expect_is("formula") summary[[1]]$fns$`std dev` %>% expect_is("formula") @@ -217,45 +345,661 @@ test_that("the `summary_rows()` function works correctly", { summary[[2]]$formatter_options %>% expect_is("list") - # Create a table with summary rows for the `A` and `C` groups; - # the 3 summary rows for these groups represent the mean, sum, - # and standard deviation of `value` + # Expect that `summary[[1|2]]$formatter_options` are both + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + summary[[2]]$formatter_options %>% + length() %>% + expect_equal(0) + + # Create a table with two sets of summary rows for all groups + # and all columns + gt_tbl <- + tbl %>% + summary_rows( + groups = TRUE, + columns = vars(open, high), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE) + ) + ) %>% + summary_rows( + groups = TRUE, + columns = vars(low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE) + ) + ) + + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect that the internal `summary` list + # object has a length of `2` since there + # were two calls of `summary_rows()` + length(summary) %>% + expect_equal(2) + + # For the two list components in `summary`, expect specific + # names within them + summary[[1]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + summary[[2]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + # Expect that `summary[[1|2]]$groups` is TRUE + summary[[1]]$groups %>% + expect_true() + + summary[[2]]$groups %>% + expect_true() + + # Expect that `summary[[1|2]]$columns` has specific values + summary[[1]]$columns %>% + expect_equal(c("open", "high")) + + summary[[2]]$columns %>% + expect_equal(c("low", "close")) + + # Expect that `summary[[1|2]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") + + summary[[2]]$fns %>% + expect_is("list") + + # Expect that the components of `summary[[1|2]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + summary[[2]]$fns$average %>% expect_is("formula") + summary[[2]]$fns$total %>% expect_is("formula") + summary[[2]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1|2]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + summary[[2]]$missing_text %>% + expect_equal("---") + + # Expect that `summary[[1|2]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + summary[[2]]$formatter %>% + expect_is("function") + + # Expect that `summary[[1|2]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + summary[[2]]$formatter_options %>% + expect_is("list") + + # Expect that `summary[[1|2]]$formatter_options` are both + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + summary[[2]]$formatter_options %>% + length() %>% + expect_equal(0) +}) + +test_that("the `summary_rows()` can make grand summaries", { + + # Create a table with a grand summary; + # the 3 summary rows for represent the + # mean, sum, and standard deviation of + # all numeric columns gt_tbl <- - gt(tbl) %>% + tbl %>% summary_rows( - groups = c("A", "C"), - columns = vars(value_1), + groups = NULL, + columns = vars(open, high, low, close), fns = list( average = ~mean(., na.rm = TRUE), total = ~sum(., na.rm = TRUE), `std dev` = ~sd(., na.rm = TRUE))) - # Extract the summary data from `gt_tbl` - summaries <- extract_summary(gt_tbl) + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect that the internal `summary` list + # object has a length of `1` since there was + # only one call of `summary_rows()` + length(summary) %>% + expect_equal(1) + + # For the single list component in `summary`, expect specific + # names within it + summary[[1]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + # Expect the `groups` provided in `summary[[1]]$groups` + # is NULL + summary[[1]]$groups %>% + expect_null() + + # Expect the `columns` provided in `summary[[1]]$columns` + # provide names for all columns + summary[[1]]$columns %>% + expect_equal(c("open", "high", "low", "close")) - # Expect that `summaries` is a list object - summaries %>% expect_is("list") + # Expect that `summary[[1]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") - # Expect that `summaries` has a length of `2` - summaries %>% + # Expect that the components of `summary[[1]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + # Expect that `summary[[1]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + # Expect that `summary[[1]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + # Create a table with a grand summary; + # the 3 summary rows for represent the + # mean, sum, and standard deviation of + # all numeric columns; split into 2 calls + # that allow for different formatting + # options + gt_tbl <- + tbl %>% + summary_rows( + groups = NULL, + columns = vars(open, high), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE)), + formatter = fmt_number, + decimals = 3) %>% + summary_rows( + groups = NULL, + columns = vars(low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE)), + formatter = fmt_number, + decimals = 5) + + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect that the internal `summary` list + # object has a length of `2` since there + # were two calls of `summary_rows()` + length(summary) %>% + expect_equal(2) + + # For the two list components in `summary`, expect specific + # names within them + summary[[1]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + summary[[2]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + # Expect that `summary[[1|2]]$groups` is TRUE + summary[[1]]$groups %>% + expect_null() + + summary[[2]]$groups %>% + expect_null() + + # Expect that `summary[[1|2]]$columns` has specific values + summary[[1]]$columns %>% + expect_equal(c("open", "high")) + + summary[[2]]$columns %>% + expect_equal(c("low", "close")) + + # Expect that `summary[[1|2]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") + + summary[[2]]$fns %>% + expect_is("list") + + # Expect that the functions used in each call + # are the same + expect_identical(summary[[1]]$fns, summary[[1]]$fns) + + # Expect that the components of `summary[[1|2]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + summary[[2]]$fns$average %>% expect_is("formula") + summary[[2]]$fns$total %>% expect_is("formula") + summary[[2]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1|2]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + summary[[2]]$missing_text %>% + expect_equal("---") + + # Expect that `summary[[1|2]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + summary[[2]]$formatter %>% + expect_is("function") + + # Expect that the formatters used in each call + # are the same + expect_identical(summary[[1]]$formatter, summary[[2]]$formatter) + + # Expect that `summary[[1|2]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + summary[[2]]$formatter_options %>% + expect_is("list") + + # Expect that `summary[[1|2]]$formatter_options` are both + # of length 1 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(1) + + summary[[2]]$formatter_options %>% length() %>% + expect_equal(1) + + # Expect that `summary[[1|2]]$formatter_options` + # are both named `decimals` + summary[[1]]$formatter_options %>% + names() %>% + expect_equal("decimals") + + summary[[2]]$formatter_options %>% + names() %>% + expect_equal("decimals") + + # Expect that the `summary[[1|2]]$formatter_options` + # `decimals` options have specific values + summary[[1]]$formatter_options[[1]] %>% + expect_equal(3) + + summary[[2]]$formatter_options[[1]] %>% + expect_equal(5) + + # Create a table with groupwsie summaries + # and a grand summary; all summary rows + # represent the mean, sum, and standard + # deviation of all numeric columns; + gt_tbl <- + tbl %>% + summary_rows( + groups = TRUE, + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE)) + ) %>% + summary_rows( + groups = NULL, + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE)) + ) + + # Extract the internal `summary` object + summary <- attr(gt_tbl, "summary", exact = TRUE) + + # Expect that the internal `summary` list + # object has a length of `2` since there + # were two calls of `summary_rows()` + length(summary) %>% expect_equal(2) - # Expect that `summaries` the names `A` and `C` - summaries %>% + # For the two list components in `summary`, expect specific + # names within them + summary[[1]] %>% + names() %>% + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) + + summary[[2]] %>% names() %>% - expect_equal(c("A", "C")) + expect_equal( + c("groups", "columns", "fns", "summary_labels", + "missing_text", "formatter", "formatter_options") + ) - # Expect that each of the components contains a `tibble` - summaries[[1]] %>% - expect_is(c("tbl_df", "tbl", "data.frame")) + # Expect that `summary[[1]]$groups` is TRUE + summary[[1]]$groups %>% + expect_true() - summaries[[2]] %>% - expect_is(c("tbl_df", "tbl", "data.frame")) + # Expect that `summary[[1]]$groups` is NULL + summary[[2]]$groups %>% + expect_null() + + # Expect that `summary[[1|2]]$columns` has specific values + summary[[1]]$columns %>% + expect_equal(c("open", "high", "low", "close")) + + summary[[2]]$columns %>% + expect_equal(c("open", "high", "low", "close")) + + # Expect that `summary[[1|2]]$fns` is a `list` object + summary[[1]]$fns %>% + expect_is("list") + + summary[[2]]$fns %>% + expect_is("list") + + # Expect that the functions used in each call + # are the same + expect_identical(summary[[1]]$fns, summary[[1]]$fns) + + # Expect that the components of `summary[[1|2]]$fns` are formulas + summary[[1]]$fns$average %>% expect_is("formula") + summary[[1]]$fns$total %>% expect_is("formula") + summary[[1]]$fns$`std dev` %>% expect_is("formula") + summary[[2]]$fns$average %>% expect_is("formula") + summary[[2]]$fns$total %>% expect_is("formula") + summary[[2]]$fns$`std dev` %>% expect_is("formula") + + # Expect that `summary[[1|2]]$missing_text` has a specific value + summary[[1]]$missing_text %>% + expect_equal("---") + + summary[[2]]$missing_text %>% + expect_equal("---") - # Expect an error in the case where `extract_summary()` - # is called on a gt table object where there is no summary - expect_error( - gt(mtcars) %>% - extract_summary()) + # Expect that `summary[[1|2]]$formatter` is a `function` object + summary[[1]]$formatter %>% + expect_is("function") + + summary[[2]]$formatter %>% + expect_is("function") + + # Expect that the formatters used in each call + # are the same + expect_identical(summary[[1]]$formatter, summary[[2]]$formatter) + + # Expect that `summary[[1|2]]$formatter_options` is a list + summary[[1]]$formatter_options %>% + expect_is("list") + + summary[[2]]$formatter_options %>% + expect_is("list") + + # Expect that `summary[[1|2]]$formatter_options` are both + # of length 0 + summary[[1]]$formatter_options %>% + length() %>% + expect_equal(0) + + summary[[2]]$formatter_options %>% + length() %>% + expect_equal(0) +}) + +test_that("`groups = FALSE` returns data unchanged", { + + # Expect that using `groups = FALSE` with + # `summary_rows()` creates no summary rows + expect_equal( + tbl %>% as_raw_html(), + tbl %>% + summary_rows( + groups = FALSE, + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE))) %>% + as_raw_html() + ) +}) + +test_that("summary rows can be created when there is no stub", { + + # Create a table based on `sp500`, with + # four columns of values + tbl_2 <- + sp500 %>% + dplyr::filter( + date >= "2015-01-05" & + date <="2015-01-09" + ) %>% + dplyr::arrange(date) %>% + dplyr::select(-adj_close, -volume) %>% + gt() + + # Create a gt table with a grand summary; + # the table doesn't have a stub (and there + # are no row groups) + gt_tbl <- + tbl_2 %>% + summary_rows( + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE)) + ) + + # Extract `output_df` in the HTML context and + # expect that the `rowname` column is entirely + # filled with empty strings + expect_equal( + (gt_tbl %>% render_formats_test("html"))[["rowname"]], + rep("", 5) + ) + + # Expect that the grand summary row labels are + # available in the rendered output table + expect_match( + gt_tbl %>% + as_raw_html(inline_css = FALSE), + "") + + expect_match( + gt_tbl %>% + as_raw_html(inline_css = FALSE), + "") + + expect_match( + gt_tbl %>% + as_raw_html(inline_css = FALSE), + "") +}) + +test_that("extracting a summary from a gt table is possible", { + + # Create a table with summary rows for + # the `W02` and `W03` groups; the 3 summary + # rows represent the mean, sum, and standard + # deviation of all numeric columns; extract + # the internal summary with `extract_summary()` + gt_tbl_summary_groupwise <- + tbl %>% + summary_rows( + groups = c("W02", "W03"), + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE))) %>% + extract_summary() + + # Expect that the summary object is a list + expect_is(gt_tbl_summary_groupwise, "list") + + # Expect that the length of the list is `2` + expect_equal(length(gt_tbl_summary_groupwise), 2) + + # Expect specific names for the list components + expect_equal( + names(gt_tbl_summary_groupwise), + c("W02", "W03") + ) + + # Expect that each component of the list inherits + # from `tbl_df` + expect_is(gt_tbl_summary_groupwise[[1]], "tbl_df") + expect_is(gt_tbl_summary_groupwise[[2]], "tbl_df") + + # Expect specific column names for each of the + # tibbles in `gt_tbl_summary_groupwise` + expect_equal( + names(gt_tbl_summary_groupwise[[1]]), + c("groupname", "rowname", "open", "high", "low", "close") + ) + + expect_equal( + names(gt_tbl_summary_groupwise[[2]]), + c("groupname", "rowname", "open", "high", "low", "close") + ) + + # Expect specific values in each of the tibbles + expect_equal( + gt_tbl_summary_groupwise[[1]]$open, + c(2035.23998, 10176.19990, 23.65756), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[1]]$high, + c(2048.56198, 10242.80990, 17.47612), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[1]]$low, + c(2016.8540, 10084.2699, 18.5372), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[1]]$close, + c(2031.2080, 10156.0400, 22.9171), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[2]]$open, + c(2020.42200, 10102.11000, 20.17218), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[2]]$high, + c(2033.28798, 10166.43990, 18.33064), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[2]]$low, + c(1999.77198, 9998.85990, 15.20847), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_groupwise[[2]]$close, + c(2014.9300, 10074.6500, 13.8957), tolerance = .002 + ) + + # Create a table with a grand summary; the 3 + # summary rows represent the mean, sum, and + # standard deviation of all numeric columns; + # extract the internal summary with `extract_summary()` + gt_tbl_summary_grand <- + tbl %>% + summary_rows( + columns = vars(open, high, low, close), + fns = list( + average = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + `std dev` = ~sd(., na.rm = TRUE))) %>% + extract_summary() + + # Expect that the summary object is a list + expect_is(gt_tbl_summary_grand, "list") + + # Expect that the length of the list is `1` + expect_equal(length(gt_tbl_summary_grand), 1) + + # Expect a specific name for the one list component + expect_equal(names(gt_tbl_summary_grand), "::GRAND_SUMMARY") + + # Expect that the single component of the list inherits + # from `tbl_df` + expect_is(gt_tbl_summary_grand[[1]], "tbl_df") + + # Expect specific column names for the + # tibble in `gt_tbl_summary_grand` + expect_equal( + names(gt_tbl_summary_grand[[1]]), + c("groupname", "rowname", "open", "high", "low", "close") + ) + + # Expect specific values in the tibble + expect_equal( + gt_tbl_summary_grand[[1]]$open, + c(2027.83099, 20278.30990, 22.14929), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_grand[[1]]$high, + c(2040.92498, 20409.24980, 18.70516), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_grand[[1]]$low, + c(2008.31298, 20083.12980, 18.34602), tolerance = .002 + ) + + expect_equal( + gt_tbl_summary_grand[[1]]$close, + c(2023.06900, 20230.69000, 19.82022), tolerance = .002 + ) + + # Expect an error with `extract_summary()` if there + # are no summaries (i.e., `summary_rows()` wasn't used) + expect_error(tbl %>% extract_summary()) }) diff --git a/tests/testthat/test-tab_footnote.R b/tests/testthat/test-tab_footnote.R index f399213704..29de64fce2 100644 --- a/tests/testthat/test-tab_footnote.R +++ b/tests/testthat/test-tab_footnote.R @@ -10,11 +10,14 @@ data <- cols_hide(columns = "vs") %>% tab_row_group( group = "Mercs", - rows = contains("Merc") + rows = contains("Merc"), ) %>% tab_row_group( group = "Mazdas", - rows = contains("Mazda") + rows = contains("Mazda"), + ) %>% + tab_row_group( + others = "Others" ) %>% tab_spanner( label = "gear_carb_cyl", @@ -36,6 +39,12 @@ data <- fns = list( ~mean(., na.rm = TRUE), ~sum(., na.rm = TRUE)) + ) %>% + summary_rows( + columns = vars(hp, wt), + fns = list( + ~mean(., na.rm = TRUE), + ~sum(., na.rm = TRUE)) ) # Create a table from `gtcars` that has footnotes @@ -67,6 +76,50 @@ data_2 <- tab_spanner(label = "make and model", columns = vars(mfr, model)) %>% tab_spanner(label = "specs and pricing", columns = vars(drivetrain, msrp)) + +# Create a table from `gtcars` that has footnotes +# in group summary and grand summary cells +data_3 <- + gtcars %>% + dplyr::filter(ctry_origin == "Germany") %>% + dplyr::group_by(mfr) %>% + dplyr::top_n(3, msrp) %>% + dplyr::ungroup() %>% + dplyr::select(mfr, model, drivetrain, msrp) %>% + gt(rowname_col = "model", groupname_col = "mfr") %>% + summary_rows( + groups = c("BMW", "Audi"), + columns = vars(msrp), + fns = list( + ~mean(., na.rm = TRUE), + ~min(., na.rm = TRUE)) + ) %>% + summary_rows( + columns = vars(msrp), + fns = list( + ~min(., na.rm = TRUE), + ~max(., na.rm = TRUE)) + ) %>% + tab_footnote( + footnote = "Average price for BMW and Audi.", + locations = cells_summary( + groups = c("BMW", "Audi"), + columns = vars(msrp), + rows = starts_with("me")) + ) %>% + tab_footnote( + footnote = "Maximum price across all cars.", + locations = cells_grand_summary( + columns = vars(msrp), + rows = starts_with("ma")) + ) %>% + tab_footnote( + footnote = "Minimum price across all cars.", + locations = cells_grand_summary( + columns = vars(msrp), + rows = starts_with("mi")) + ) + # Function to skip tests if Suggested packages not available on system check_suggests <- function() { skip_if_not_installed("rvest") @@ -103,7 +156,9 @@ test_that("the `tab_footnote()` function works correctly", { footnote = "Column labels and stub footnote.", locations = list( cells_column_labels(columns = TRUE), - cells_stub(rows = TRUE))) + cells_stub(rows = TRUE) + ) + ) # Expect that the internal `footnotes_df` data frame will have # its `locname` column entirely populated with `columns_columns` @@ -125,7 +180,8 @@ test_that("the `tab_footnote()` function works correctly", { data %>% tab_footnote( footnote = "Stub cell footnote.", - locations = cells_stub(rows = "Merc 240D")) + locations = cells_stub(rows = "Merc 240D") + ) # Expect that the internal `footnotes_df` data frame will have # a single row @@ -138,14 +194,16 @@ test_that("the `tab_footnote()` function works correctly", { expect_attr_equal( tab, "footnotes_df", c("stub", "5", NA_character_, NA_character_, "8", - "Stub cell footnote.")) + "Stub cell footnote.") + ) # Apply a footnote to the table title tab <- data %>% tab_footnote( footnote = "Title footnote.", - locations = cells_title(groups = "title")) + locations = cells_title(groups = "title") + ) # Expect that the internal `footnotes_df` data frame will have # a single row @@ -158,14 +216,16 @@ test_that("the `tab_footnote()` function works correctly", { expect_attr_equal( tab, "footnotes_df", c("title", "1", NA_character_, NA_character_, NA_character_, - "Title footnote.")) + "Title footnote.") + ) # Apply a footnote to the table subtitle tab <- data %>% tab_footnote( footnote = "Subtitle footnote.", - locations = cells_title(groups = "subtitle")) + locations = cells_title(groups = "subtitle") + ) # Expect that the internal `footnotes_df` data frame will have # a single row @@ -178,7 +238,8 @@ test_that("the `tab_footnote()` function works correctly", { expect_attr_equal( tab, "footnotes_df", c("subtitle", "2", NA_character_, NA_character_, NA_character_, - "Subtitle footnote.")) + "Subtitle footnote.") + ) # Apply a footnote to a single cell in a group summary section tab <- @@ -186,7 +247,8 @@ test_that("the `tab_footnote()` function works correctly", { tab_footnote( footnote = "Summary cell footnote.", locations = cells_summary( - groups = "Mercs", columns = "hp", rows = 2)) + groups = "Mercs", columns = "hp", rows = 2) + ) # Expect that the internal `footnotes_df` data frame will have # a single row @@ -199,7 +261,106 @@ test_that("the `tab_footnote()` function works correctly", { expect_attr_equal( tab, "footnotes_df", c("summary_cells", "5", "Mercs", "hp", "2", - "Summary cell footnote.")) + "Summary cell footnote.") + ) + + # Expect an error if columns couldn't be resolved + expect_error( + data %>% + tab_footnote( + footnote = "Summary cell footnote.", + locations = cells_summary( + groups = "Mercs", columns = starts_with("x"), rows = 2) + ) + ) + + # Expect an error if rows couldn't be resolved + expect_error( + data %>% + tab_footnote( + footnote = "Summary cell footnote.", + locations = cells_summary( + groups = "Mercs", columns = starts_with("m"), rows = starts_with("x")) + ) + ) + + # Apply a footnote to a single cell in a grand + # summary section + tab <- + data %>% + tab_footnote( + footnote = "Grand summary cell footnote.", + locations = cells_grand_summary( + columns = vars(wt), rows = starts_with("s") + ) + ) + + # Expect that the internal `footnotes_df` data frame + # will have a single row + attr(tab, "footnotes_df", exact = TRUE) %>% + nrow() %>% + expect_equal(1) + + # Expect certain values for each of the columns in the + # single-row `footnotes_df` data frame + expect_attr_equal( + tab, "footnotes_df", + c("grand_summary_cells", "6", NA, "wt", "2", + "Grand summary cell footnote.") + ) + + # Expect an error if columns couldn't be resolved + expect_error( + data %>% + tab_footnote( + footnote = "Grand summary cell footnote.", + locations = cells_grand_summary( + columns = starts_with("x"), rows = 2) + ) + ) + + # Expect an error if rows couldn't be resolved + expect_error( + data %>% + tab_footnote( + footnote = "Grand summary cell footnote.", + locations = cells_grand_summary( + columns = starts_with("m"), rows = starts_with("x")) + ) + ) + + # Apply a footnote to a single cell in a group + # summary section, and, to a single cell in a grand + # summary section + tab <- + data %>% + tab_footnote( + footnote = "Summary cell footnote.", + locations = cells_summary( + groups = "Mercs", columns = "hp", rows = 2) + ) %>% + tab_footnote( + footnote = "Grand summary cell footnote.", + locations = cells_grand_summary( + columns = vars(wt), rows = starts_with("s") + ) + ) + + # Expect that the internal `footnotes_df` data frame + # will have two rows + attr(tab, "footnotes_df", exact = TRUE) %>% + nrow() %>% + expect_equal(2) + + # Expect certain values for each of the columns in the + # double-row `footnotes_df` data frame + expect_attr_equal( + tab, "footnotes_df", + c("summary_cells", "grand_summary_cells", + "5", "6", "Mercs", NA, "hp", "wt", "2", "2", + "Summary cell footnote.", + "Grand summary cell footnote.") + ) # Apply a footnote to the `Mazdas` stub group cell tab <- @@ -208,8 +369,8 @@ test_that("the `tab_footnote()` function works correctly", { footnote = "Group cell footnote.", locations = cells_group(groups = "Mazdas")) - # Expect that the internal `footnotes_df` data frame will have - # a single row + # Expect that the internal `footnotes_df` data frame + # will have a single row attr(tab, "footnotes_df", exact = TRUE) %>% nrow() %>% expect_equal(1) @@ -392,5 +553,122 @@ test_that("the `tab_footnote()` function works correctly", { tbl_html %>% selection_text(selection = "[class='gt_footnote_glyph']") %>% expect_equal(rep(as.character(1:4), 2)) +}) + +test_that("the `apply_footnotes_to_output()` function works correctly", { + + # Build the `data_3` object (using the `html` context) + # and obtain the `built_data` list object + built_data <- build_data(data_3, context = "html") + + # Extract `footnotes_resolved` and `list_of_summaries` + footnotes_resolved <- built_data$footnotes_resolved + list_of_summaries <- built_data$list_of_summaries + + # Expect that the `footnotes_resolved` object inherits + # from `tbl_df` + expect_is(footnotes_resolved, "tbl_df") + + # Expect that there are specific column names in + # this tibble + expect_equal( + colnames(footnotes_resolved), + c("locname", "locnum", "grpname", "colname", "rownum", + "text", "colnum", "fs_id") + ) + + # Expect that there are 4 rows in this tibble + expect_equal(nrow(footnotes_resolved), 4) + + # Expect specific values to be in `footnotes_resolved` + expect_equal( + footnotes_resolved$locname, + c("summary_cells", "summary_cells", + "grand_summary_cells", "grand_summary_cells") + ) + expect_equal(footnotes_resolved$locnum, c(5, 5, 6, 6)) + expect_equal(footnotes_resolved$grpname, c("BMW", "Audi", NA, NA)) + expect_equal(footnotes_resolved$colname, rep("msrp", 4)) + expect_equal(footnotes_resolved$rownum, c(3.01, 6.01, 1.00, 2.00)) + expect_equal( + footnotes_resolved$text, + c("Average price for BMW and Audi.", "Average price for BMW and Audi.", + "Minimum price across all cars.", "Maximum price across all cars.") + ) + expect_equal(footnotes_resolved$colnum, rep(2, 4)) + expect_equal(footnotes_resolved$fs_id, c("1", "1", "2", "3")) + + # Expect that the list of summaries has length `2` + expect_equal(length(list_of_summaries), 2) + + # Expect specific names in the `list_of_summaries` list + expect_equal( + names(list_of_summaries), + c("summary_df_data_list", "summary_df_display_list") + ) + + # Expect three tibbles in the `summary_df_data_list` component + expect_equal(length(list_of_summaries$summary_df_data_list), 3) + + # Expect three tibbles in the `summary_df_display_list` component + expect_equal(length(list_of_summaries$summary_df_display_list), 3) + + # Expect specific names for the subcomponents of the + # `summary_df_data_list` and `summary_df_data_list` + # parent components + expect_equal( + names(list_of_summaries$summary_df_data_list), + c("BMW", "Audi", "::GRAND_SUMMARY") + ) + expect_equal( + names(list_of_summaries$summary_df_display_list), + c("::GRAND_SUMMARY", "Audi", "BMW") + ) + + # Expect formatted cell values with no HTML footnote markup + expect_equal( + list_of_summaries$summary_df_display_list$`::GRAND_SUMMARY`$msrp, + c("56,000.00", "140,700.00") + ) + + expect_equal( + list_of_summaries$summary_df_display_list$Audi$msrp, + c("113,233.33", "108,900.00") + ) + + expect_equal( + list_of_summaries$summary_df_display_list$BMW$msrp, + c("116,066.67", "94,100.00") + ) + + # Use the `apply_footnotes_to_summary()` function to modify + # the cell values in the `list_of_summaries$summary_df_display_list` + # subcomponent of `list_of_summaries` + applied_footnotes <- + apply_footnotes_to_summary(list_of_summaries, footnotes_resolved) + + # Expect no change in the `summary_df_data_list` subcomponent + # as a result of the transformation + expect_equivalent( + list_of_summaries$summary_df_data_list, + applied_footnotes$summary_df_data_list + ) + + # Expect formatted cell values with HTML footnote markup + expect_equal( + applied_footnotes$summary_df_display_list$`::GRAND_SUMMARY`$msrp, + c("56,000.002", + "140,700.003") + ) + + expect_equal( + applied_footnotes$summary_df_display_list$Audi$msrp, + c("113,233.331", "108,900.00") + ) + + expect_equal( + applied_footnotes$summary_df_display_list$BMW$msrp, + c("116,066.671", "94,100.00") + ) }) diff --git a/tests/testthat/test-tab_options.R b/tests/testthat/test-tab_options.R index 88d80d09bb..92674cf150 100644 --- a/tests/testthat/test-tab_options.R +++ b/tests/testthat/test-tab_options.R @@ -517,17 +517,17 @@ test_that("the internal `opts_df` table can be correctly modified", { dplyr::filter(parameter == "row_padding") %>% dplyr::pull(value), attr(tbl_html, "opts_df", exact = TRUE) %>% dplyr::filter(parameter == "row_padding") %>% dplyr::pull(value)) %>% - expect_equal(c("10px", "8px")) + expect_equal(c("8px", "8px")) # Modify the `row.padding` option using just a numeric value - tbl_html <- data %>% tab_options(row.padding = 8) + tbl_html <- data %>% tab_options(row.padding = 6) # Compare before and after values c(opts_df_1 %>% dplyr::filter(parameter == "row_padding") %>% dplyr::pull(value), attr(tbl_html, "opts_df", exact = TRUE) %>% dplyr::filter(parameter == "row_padding") %>% dplyr::pull(value)) %>% - expect_equal(c("10px", "8px")) + expect_equal(c("8px", "6px")) # Modify the `summary_row.background.color` tbl_html <- data %>% tab_options(summary_row.background.color = "pink") @@ -547,7 +547,7 @@ test_that("the internal `opts_df` table can be correctly modified", { dplyr::filter(parameter == "summary_row_padding") %>% dplyr::pull(value), attr(tbl_html, "opts_df", exact = TRUE) %>% dplyr::filter(parameter == "summary_row_padding") %>% dplyr::pull(value)) %>% - expect_equal(c("6px", "4px")) + expect_equal(c("8px", "4px")) # Modify the `summary_row.padding` option using just a numeric value tbl_html <- data %>% tab_options(summary_row.padding = 4) @@ -557,7 +557,7 @@ test_that("the internal `opts_df` table can be correctly modified", { dplyr::filter(parameter == "summary_row_padding") %>% dplyr::pull(value), attr(tbl_html, "opts_df", exact = TRUE) %>% dplyr::filter(parameter == "summary_row_padding") %>% dplyr::pull(value)) %>% - expect_equal(c("6px", "4px")) + expect_equal(c("8px", "4px")) # Modify the `summary_row.text_transform` tbl_html <- data %>% tab_options(summary_row.text_transform = "lowercase") @@ -569,6 +569,46 @@ test_that("the internal `opts_df` table can be correctly modified", { dplyr::filter(parameter == "summary_row_text_transform") %>% dplyr::pull(value)) %>% expect_equal(c("inherit", "lowercase")) + # Modify the `grand_summary_row.background.color` + tbl_html <- data %>% tab_options(grand_summary_row.background.color = "pink") + + # Compare before and after values + c(opts_df_1 %>% + dplyr::filter(parameter == "grand_summary_row_background_color") %>% dplyr::pull(value), + attr(tbl_html, "opts_df", exact = TRUE) %>% + dplyr::filter(parameter == "grand_summary_row_background_color") %>% dplyr::pull(value)) %>% + expect_equal(c(NA_character_, "pink")) + + # Modify the `grand_summary_row.padding` + tbl_html <- data %>% tab_options(grand_summary_row.padding = px(4)) + + # Compare before and after values + c(opts_df_1 %>% + dplyr::filter(parameter == "grand_summary_row_padding") %>% dplyr::pull(value), + attr(tbl_html, "opts_df", exact = TRUE) %>% + dplyr::filter(parameter == "grand_summary_row_padding") %>% dplyr::pull(value)) %>% + expect_equal(c("8px", "4px")) + + # Modify the `grand_summary_row.padding` option using just a numeric value + tbl_html <- data %>% tab_options(grand_summary_row.padding = 4) + + # Compare before and after values + c(opts_df_1 %>% + dplyr::filter(parameter == "grand_summary_row_padding") %>% dplyr::pull(value), + attr(tbl_html, "opts_df", exact = TRUE) %>% + dplyr::filter(parameter == "grand_summary_row_padding") %>% dplyr::pull(value)) %>% + expect_equal(c("8px", "4px")) + + # Modify the `grand_summary_row.text_transform` + tbl_html <- data %>% tab_options(grand_summary_row.text_transform = "lowercase") + + # Compare before and after values + c(opts_df_1 %>% + dplyr::filter(parameter == "grand_summary_row_text_transform") %>% dplyr::pull(value), + attr(tbl_html, "opts_df", exact = TRUE) %>% + dplyr::filter(parameter == "grand_summary_row_text_transform") %>% dplyr::pull(value)) %>% + expect_equal(c("inherit", "lowercase")) + # Modify the `footnote.font.size` tbl_html <- data %>% tab_options(footnote.font.size = px(12)) diff --git a/tests/testthat/test-tab_style.R b/tests/testthat/test-tab_style.R index 8af6951d61..62ea98b3db 100644 --- a/tests/testthat/test-tab_style.R +++ b/tests/testthat/test-tab_style.R @@ -15,6 +15,9 @@ data <- group = "Mazdas", rows = contains("Mazda") ) %>% + tab_row_group( + others = "Others" + ) %>% tab_spanner( label = "gear_carb_cyl", columns = vars(gear, carb, cyl) @@ -35,6 +38,12 @@ data <- fns = list( ~mean(., na.rm = TRUE), ~sum(., na.rm = TRUE)) + ) %>% + summary_rows( + columns = vars(hp, wt), + fns = list( + ~mean(., na.rm = TRUE), + ~sum(., na.rm = TRUE)) ) # Function to skip tests if Suggested packages not available on system @@ -176,6 +185,69 @@ test_that("a gt table can store the correct style statements", { c("summary_cells", "5", "Mercs", "hp", "2", "background-color:green;color:white;")) + # Expect an error if columns couldn't be resolved + expect_error( + data %>% + tab_style( + style = cells_styles(bkgd_color = "green", text_color = "white"), + locations = cells_summary( + groups = "Mercs", columns = starts_with("x"), rows = 2) + ) + ) + + # Expect an error if rows couldn't be resolved + expect_error( + data %>% + tab_style( + style = cells_styles(bkgd_color = "green", text_color = "white"), + locations = cells_summary( + groups = "Mercs", columns = starts_with("m"), rows = starts_with("x")) + ) + ) + + # Apply a red background with white text to a single cell in + # the grand summary section + tbl_html <- + data %>% + tab_style( + style = cells_styles(bkgd_color = "red", text_color = "white"), + locations = cells_grand_summary( + columns = "hp", rows = vars(sum)) + ) + + # Expect that the internal `styles_df` data frame will have + # a single row + attr(tbl_html, "styles_df", exact = TRUE) %>% + nrow() %>% + expect_equal(1) + + # Expect certain values for each of the columns in the + # single-row `styles_df` data frame + expect_attr_equal( + tbl_html, "styles_df", + c("grand_summary_cells", "6", NA, "hp", "2", + "background-color:red;color:white;")) + + # Expect an error if columns couldn't be resolved + expect_error( + data %>% + tab_style( + style = cells_styles(bkgd_color = "red", text_color = "white"), + locations = cells_grand_summary( + columns = starts_with("x"), rows = 2) + ) + ) + + # Expect an error if rows couldn't be resolved + expect_error( + data %>% + tab_style( + style = cells_styles(bkgd_color = "red", text_color = "white"), + locations = cells_grand_summary( + columns = starts_with("m"), rows = starts_with("x")) + ) + ) + # Apply a `yellow` background to the `Mazdas` stub group cell tbl_html <- data %>% diff --git a/tests/testthat/test-table_parts.R b/tests/testthat/test-table_parts.R index ac05505871..74b4a7a4a7 100644 --- a/tests/testthat/test-table_parts.R +++ b/tests/testthat/test-table_parts.R @@ -286,6 +286,12 @@ test_that("a gt table contains custom styles at the correct locations", { ~mean(., na.rm = TRUE), ~sum(., na.rm = TRUE)) ) %>% + summary_rows( + columns = vars(hp, wt, qsec), + fns = list( + ~mean(., na.rm = TRUE), + ~sum(., na.rm = TRUE)) + ) %>% tab_style( style = cells_styles(bkgd_color = "lightgray"), locations = list( @@ -309,6 +315,10 @@ test_that("a gt table contains custom styles at the correct locations", { locations = cells_summary( groups = "Mercs", columns = "hp", rows = 2) ) %>% + tab_style( + style = cells_styles(bkgd_color = "purple", text_color = "white"), + locations = cells_grand_summary(columns = "hp", rows = 2) + ) %>% tab_style( style = cells_styles(bkgd_color = "lightgreen"), locations = cells_column_labels(groups = "gear_carb_cyl") @@ -354,6 +364,12 @@ test_that("a gt table contains custom styles at the correct locations", { rvest::html_text("[class='gt_row gt_summary_row gt_center']") %>% expect_equal("943.00") + # Expect that the grand summary cell (`sum`/`hp`) is styled + tbl_html %>% + rvest::html_nodes("[style='background-color:purple;color:white;']") %>% + rvest::html_text("[class='gt_row gt_grand_summary_row gt_center']") %>% + expect_equal("4,694.00") + # Expect that some column labels (e.g., `disp`, `wt`, etc.) are # styled with a lightgrey background (tbl_html %>% diff --git a/tests/testthat/test-util_functions.R b/tests/testthat/test-util_functions.R index 8905fd7917..442f4feb84 100644 --- a/tests/testthat/test-util_functions.R +++ b/tests/testthat/test-util_functions.R @@ -361,7 +361,7 @@ test_that("the `get_css_tbl()` function works correctly", { css_tbl %>% expect_is(c("tbl_df", "tbl", "data.frame")) - css_tbl %>% dim() %>% expect_equal(c(103, 4)) + css_tbl %>% dim() %>% expect_equal(c(110, 4)) css_tbl %>% colnames() %>% @@ -410,7 +410,7 @@ test_that("the `inline_html_styles()` function works correctly", { # Expect that the style rule from `tab_style` is a listed value along with # the inlined rules derived from the CSS classes expect_true( - grepl("style=\"padding:10px;margin:10px;vertical-align:middle;text-align:right;font-variant-numeric:tabular-nums;font-size:10px;\"", inlined_html) + grepl("style=\"padding:8px;margin:10px;vertical-align:middle;text-align:right;font-variant-numeric:tabular-nums;font-size:10px;\"", inlined_html) ) # Create a gt table with a custom style in the title and subtitle From ad55d8c537204d0bd8fb535be41de2112013c7b6 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Thu, 25 Apr 2019 18:08:18 -0400 Subject: [PATCH 5/8] Store empty-string value in `sep` vector (#274) * Store empty-string value in `sep` vector * Add several testthat tests --- R/modify_columns.R | 6 ++++++ tests/testthat/test-cols_merge.R | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/R/modify_columns.R b/R/modify_columns.R index d89a97c4a5..3e55886fe9 100644 --- a/R/modify_columns.R +++ b/R/modify_columns.R @@ -759,6 +759,9 @@ cols_merge <- function(data, attr(data, "col_merge")[["pattern"]] <- c(attr(data, "col_merge")[["pattern"]], pattern) + attr(data, "col_merge")[["sep"]] <- + c(attr(data, "col_merge")[["sep"]], "") + attr(data, "col_merge")[["col_1"]] <- c(attr(data, "col_merge")[["col_1"]], col_1) @@ -878,6 +881,9 @@ cols_merge_uncert <- function(data, attr(data, "col_merge")[["pattern"]] <- c(attr(data, "col_merge")[["pattern"]], pattern) + attr(data, "col_merge")[["sep"]] <- + c(attr(data, "col_merge")[["sep"]], "") + attr(data, "col_merge")[["col_1"]] <- c(attr(data, "col_merge")[["col_1"]], col_val) diff --git a/tests/testthat/test-cols_merge.R b/tests/testthat/test-cols_merge.R index 96a928e71a..174e29a41c 100644 --- a/tests/testthat/test-cols_merge.R +++ b/tests/testthat/test-cols_merge.R @@ -42,6 +42,9 @@ test_that("the function `cols_merge()` works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} ({2})") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("wt") @@ -63,6 +66,9 @@ test_that("the function `cols_merge()` works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} ({2})") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("wt") @@ -88,6 +94,9 @@ test_that("the function `cols_merge()` works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern[[1]] %>% expect_equal("{1} ({2})") + attr(tbl_html, "col_merge", exact = TRUE)$sep[[1]] %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1[1] %>% names() %>% expect_equal("wt") @@ -99,6 +108,9 @@ test_that("the function `cols_merge()` works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern[[2]] %>% expect_equal("{1}-{2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep[[2]] %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1[2] %>% names() %>% expect_equal("carb") @@ -125,6 +137,9 @@ test_that("the `cols_merge_uncert()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} ± {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("col_2") @@ -145,6 +160,9 @@ test_that("the `cols_merge_uncert()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} ± {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("col_2") @@ -168,6 +186,9 @@ test_that("the `cols_merge_uncert()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern[[1]] %>% expect_equal("{1} ± {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep[[1]] %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1[1] %>% names() %>% expect_equal("col_2") @@ -179,6 +200,9 @@ test_that("the `cols_merge_uncert()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern[[2]] %>% expect_equal("{1} ± {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep[[2]] %>% + expect_equal("") + attr(tbl_html, "col_merge", exact = TRUE)$col_1[2] %>% names() %>% expect_equal("col_4") @@ -205,6 +229,9 @@ test_that("the `cols_merge_range()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} {sep} {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("---") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("col_2") @@ -225,6 +252,9 @@ test_that("the `cols_merge_range()` function works correctly", { attr(tbl_html, "col_merge", exact = TRUE)$pattern %>% expect_equal("{1} {sep} {2}") + attr(tbl_html, "col_merge", exact = TRUE)$sep %>% + expect_equal("---") + attr(tbl_html, "col_merge", exact = TRUE)$col_1 %>% names() %>% expect_equal("col_2") From c5d7a5275288f6b5b7e91ccb95a680f016ea5646 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Fri, 26 Apr 2019 15:05:49 -0400 Subject: [PATCH 6/8] Move roxygen documentation to Markdown (#253) * Add Roxygen Markdown option in DESCRIPTION * Transform all roxygen documentation to Markdown * Update help files using roxygen * Update roxygen documentation * Update help files using roxygen * Update roxygen @param statements * Update help files using roxygen * Convert some roxygen docs to Markdown * Update help files using roxygen --- DESCRIPTION | 1 + R/as_latex.R | 13 +- R/as_raw_html.R | 17 +- R/as_rtf.R | 8 +- R/data_color.R | 108 +++++---- R/datasets.R | 186 +++++++-------- R/extract_summary.R | 10 +- R/format_data.R | 483 ++++++++++++++++++-------------------- R/gt.R | 47 ++-- R/gt_preview.R | 40 ++-- R/gtsave.R | 50 ++-- R/helpers.R | 137 ++++++----- R/image.R | 122 +++++----- R/info_tables.R | 102 ++++---- R/modify_columns.R | 363 ++++++++++++++-------------- R/modify_rows.R | 16 +- R/print.R | 4 +- R/render_as_html.R | 6 +- R/resolver.R | 32 +-- R/shiny.R | 16 +- R/summary_rows.R | 69 +++--- R/tab_footnote.R | 53 ++--- R/tab_options.R | 66 +++--- R/tab_style.R | 50 ++-- R/table_parts.R | 78 +++--- R/text_transform.R | 24 +- R/utils.R | 28 +-- R/zzz.R | 4 +- man/adjust_luminance.Rd | 16 +- man/as_latex.Rd | 13 +- man/as_raw_html.Rd | 17 +- man/as_rtf.Rd | 6 +- man/cells_styles.Rd | 57 +++-- man/cols_align.Rd | 38 ++- man/cols_hide.Rd | 25 +- man/cols_label.Rd | 34 +-- man/cols_merge.Rd | 42 ++-- man/cols_merge_range.Rd | 45 ++-- man/cols_merge_uncert.Rd | 43 ++-- man/cols_move.Rd | 36 ++- man/cols_move_to_end.Rd | 26 +- man/cols_move_to_start.Rd | 27 +-- man/cols_split_delim.Rd | 30 ++- man/countrypops.Rd | 15 +- man/data_color.Rd | 59 +++-- man/exibble.Rd | 37 ++- man/extract_summary.Rd | 4 +- man/fmt.Rd | 66 +++--- man/fmt_currency.Rd | 114 ++++----- man/fmt_date.Rd | 53 ++--- man/fmt_datetime.Rd | 68 +++--- man/fmt_markdown.Rd | 35 ++- man/fmt_missing.Rd | 43 ++-- man/fmt_number.Rd | 88 ++++--- man/fmt_passthrough.Rd | 57 ++--- man/fmt_percent.Rd | 59 ++--- man/fmt_scientific.Rd | 61 +++-- man/fmt_time.Rd | 54 ++--- man/ggplot_image.Rd | 38 ++- man/gt-options.Rd | 6 +- man/gt.Rd | 47 ++-- man/gt_output.Rd | 2 +- man/gt_preview.Rd | 42 ++-- man/gtcars.Rd | 54 ++--- man/gtsave.Rd | 37 ++- man/html.Rd | 6 +- man/info_currencies.Rd | 28 +-- man/info_date_style.Rd | 10 +- man/info_locales.Rd | 19 +- man/info_paletteer.Rd | 18 +- man/info_time_style.Rd | 10 +- man/knit_print.gt_tbl.Rd | 2 +- man/local_image.Rd | 34 ++- man/location_cells.Rd | 13 +- man/md.Rd | 6 +- man/pct.Rd | 2 +- man/pizzaplace.Rd | 48 ++-- man/print.gt_tbl.Rd | 2 +- man/px.Rd | 2 +- man/render_gt.Rd | 12 +- man/row_group_order.Rd | 19 +- man/sp500.Rd | 12 +- man/summary_rows.Rd | 64 +++-- man/sza.Rd | 14 +- man/tab_footnote.Rd | 54 ++--- man/tab_header.Rd | 13 +- man/tab_options.Rd | 67 +++--- man/tab_row_group.Rd | 32 ++- man/tab_source_note.Rd | 18 +- man/tab_spanner.Rd | 15 +- man/tab_stubhead_label.Rd | 11 +- man/tab_style.Rd | 23 +- man/test_image.Rd | 9 +- man/text_transform.Rd | 25 +- man/web_image.Rd | 24 +- 95 files changed, 2023 insertions(+), 2216 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 9adb2063b6..48bd676acc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -50,3 +50,4 @@ Suggests: shiny, xml2 VignetteBuilder: knitr +Roxygen: list(markdown = TRUE) diff --git a/R/as_latex.R b/R/as_latex.R index 75eff049ce..6883be4a93 100644 --- a/R/as_latex.R +++ b/R/as_latex.R @@ -1,13 +1,12 @@ #' Output a \pkg{gt} object as LaTeX #' -#' Get the LaTeX content from a \code{gt_tbl} object as a \code{knit_asis} -#' object. This object contains the LaTeX code and attributes that serve as -#' LaTeX dependencies (i.e., the LaTeX packages required for the table). Using -#' \code{as.character()} on the created object will result in a single-element -#' vector containing the LaTeX code. +#' Get the LaTeX content from a `gt_tbl` object as a `knit_asis` object. This +#' object contains the LaTeX code and attributes that serve as LaTeX +#' dependencies (i.e., the LaTeX packages required for the table). Using +#' `as.character()` on the created object will result in a single-element vector +#' containing the LaTeX code. #' -#' @param data a table object that is created using the \code{\link{gt}()} -#' function. +#' @param data A table object that is created using the [gt()] function. #' @import rlang #' @importFrom dplyr mutate group_by summarize ungroup rename arrange #' @importFrom stats setNames diff --git a/R/as_raw_html.R b/R/as_raw_html.R index 64280957a9..4a935ab35e 100644 --- a/R/as_raw_html.R +++ b/R/as_raw_html.R @@ -1,14 +1,13 @@ #' Get the HTML content of a \pkg{gt} table #' -#' Get the HTML content from a \code{gt_tbl} object as a single-element -#' character vector. By default, the generated HTML will have inlined styles, -#' where CSS styles (that were previously contained in CSS rule sets external to -#' the \code{
", + row_splits_grand_summary[[j]][1], + "", + row_splits_grand_summary[[j]][-1], + "
averagetotalstd dev
element}) are included as \code{style} attributes in the -#' HTML table's tags. This option is preferable when using the output HTML table -#' in an emailing context. -#' @param data a table object that is created using the \code{\link{gt}()} -#' function. -#' @param inline_css an option to supply styles to table elements as inlined CSS +#' Get the HTML content from a `gt_tbl` object as a single-element character +#' vector. By default, the generated HTML will have inlined styles, where CSS +#' styles (that were previously contained in CSS rule sets external to the +#' `
element`) are included as `style` attributes in the HTML table's +#' tags. This option is preferable when using the output HTML table in an +#' emailing context. +#' @param data A table object that is created using the [gt()] function. +#' @param inline_css An option to supply styles to table elements as inlined CSS #' styles. #' @examples #' # Use `gtcars` to create a gt table; diff --git a/R/as_rtf.R b/R/as_rtf.R index 74377f58c9..d9bda07c23 100644 --- a/R/as_rtf.R +++ b/R/as_rtf.R @@ -1,10 +1,10 @@ #' Output a \pkg{gt} object as RTF #' -#' Get the RTF content from a \code{gt_tbl} object as as a single-element -#' character vector. This object can be used with \code{writeLines()} to -#' generate a valid .rtf file that can be opened by RTF readers. +#' Get the RTF content from a `gt_tbl` object as as a single-element character +#' vector. This object can be used with `writeLines()` to generate a valid .rtf +#' file that can be opened by RTF readers. #' -#' @param data a table object that is created using the \code{gt()} function. +#' @param data a table object that is created using the `gt()` function. #' @examples #' # Use `gtcars` to create a gt table; #' # add a header and then export as diff --git a/R/data_color.R b/R/data_color.R index 66f6071428..1b379a139f 100644 --- a/R/data_color.R +++ b/R/data_color.R @@ -1,71 +1,71 @@ #' Set data cell colors using a palette or a color function #' #' It's possible to add color to data cells according to their values. The -#' \code{data_color()} function colors all rows of any \code{columns} supplied. -#' There are two ways to define how cells are colored: (1) through the use of a -#' supplied color palette, and (2) through use of a color mapping function -#' available from the \code{scales} package. The first method colorizes cell -#' data according to whether values are character or numeric. The second method -#' provides more control over how cells are colored since we provide an explicit -#' color function and thus other requirements such as bin counts, cut points, or -#' a numeric domain. Finally, we can choose whether to apply the cell-specific +#' `data_color()` function colors all rows of any `columns` supplied. There are +#' two ways to define how cells are colored: (1) through the use of a supplied +#' color palette, and (2) through use of a color mapping function available from +#' the `scales` package. The first method colorizes cell data according to +#' whether values are character or numeric. The second method provides more +#' control over how cells are colored since we provide an explicit color +#' function and thus other requirements such as bin counts, cut points, or a +#' numeric domain. Finally, we can choose whether to apply the cell-specific #' colors to either the cell background or the cell text. #' -#' The \code{col_*()} functions from the scales package can be used in the -#' \code{colors} argument. These functions map data values (\code{numeric} or -#' \code{factor}/\code{character}) to colors according to the provided palette. +#' The `col_*()` functions from the scales package can be used in the `colors` +#' argument. These functions map data values (`numeric` or `factor`/`character`) +#' to colors according to the provided palette. #' #' \itemize{ -#' \item \code{\link[scales]{col_numeric}()}: provides a simple linear mapping +#' \item [scales::col_numeric()]: provides a simple linear mapping #' from continuous numeric data to an interpolated palette. -#' \item \code{\link[scales]{col_bin}()}: provides a mapping of continuous +#' \item [scales::col_bin()]: provides a mapping of continuous #' numeric data to value-based bins. This internally uses the -#' \code{\link[base]{cut}()} function. -#' \item \code{\link[scales]{col_quantile}()}: provides a mapping of continuous +#' [base::cut()] function. +#' \item [scales::col_quantile()]: provides a mapping of continuous #' numeric data to quantiles. This internally uses the -#' \code{\link[stats]{quantile}()} function. -#' \item \code{\link[scales]{col_factor}()}: provides a mapping of factors to +#' [stats::quantile()] function. +#' \item [scales::col_factor()]: provides a mapping of factors to #' colors. If the palette is discrete and has a different number of colors than #' the number of factors, interpolation is used. #' } #' #' By default, \pkg{gt} will choose the ideal text color (for maximal contrast) #' when colorizing the background of data cells. This option can be disabled by -#' setting \code{autocolor_text} to \code{FALSE}. +#' setting `autocolor_text` to `FALSE`. #' #' Choosing the right color palette can often be difficult because it's both #' hard to discover suitable palettes and then obtain the vector of colors. To #' make this process easier we can elect to use the \pkg{paletteer} package, #' which makes a wide range of palettes from various R packages readily -#' available. The \code{\link{info_paletteer}()} information table allows us to -#' easily inspect all of the discrete color palettes available in -#' \pkg{paletteer}. We only then need to specify the \code{package} and -#' \code{palette} when calling the \code{paletteer::paletteer_d()} function, -#' and, we get the palette as a vector of hexadecimal colors. +#' available. The [info_paletteer()] information table allows us to easily +#' inspect all of the discrete color palettes available in \pkg{paletteer}. We +#' only then need to specify the `package` and `palette` when calling the +#' `paletteer::paletteer_d()` function, and, we get the palette as a vector of +#' hexadecimal colors. #' #' @inheritParams fmt_number -#' @param columns the columns wherein changes to cell data colors should occur. -#' @param colors either a color mapping function from the \code{scales} package +#' @param columns The columns wherein changes to cell data colors should occur. +#' @param colors Either a color mapping function from the `scales` package #' or a vector of colors to use for each distinct value or level in each of -#' the provided \code{columns}. The color mapping functions are: -#' \code{scales::col_quantile()}, \code{scales::col_bin()}, -#' \code{scales::col_numeric()}, and \code{scales::col_factor()}. If providing +#' the provided `columns`. The color mapping functions are: +#' `scales::col_quantile()`, `scales::col_bin()`, +#' `scales::col_numeric()`, and `scales::col_factor()`. If providing #' a vector of colors as a palette, each color value provided must either be a -#' color name (in the set of colors provided by \code{grDevices::colors()}) or +#' color name (in the set of colors provided by `grDevices::colors()`) or #' a hexadecimal string in the form of "#RRGGBB" or "#RRGGBBAA". -#' @param alpha an optional, fixed alpha transparency value that will be applied -#' to all of the \code{colors} provided if they are provided as a vector of -#' colors. If using a colorizing helper function for \code{colors} then this +#' @param alpha An optional, fixed alpha transparency value that will be applied +#' to all of the `colors` provided if they are provided as a vector of +#' colors. If using a colorizing helper function for `colors` then this #' option is ignored (each of the colorizing helper functions has its own -#' \code{alpha} argument). -#' @param apply_to which style element should the colors be applied to? Options -#' include the cell background (the default, given as \code{bkgd}) or the cell -#' text (\code{text}). -#' @param autocolor_text an option to let \pkg{gt} modify the coloring of text +#' `alpha` argument). +#' @param apply_to Which style element should the colors be applied to? Options +#' include the cell background (the default, given as `bkgd`) or the cell +#' text (`text`). +#' @param autocolor_text An option to let \pkg{gt} modify the coloring of text #' within cells undergoing background coloring. This will in some cases yield #' more optimal text-to-background color contrast. By default, this is set to -#' \code{TRUE}. -#' @return an object of class \code{gt_tbl}. +#' `TRUE`. +#' @return An object of class `gt_tbl`. #' @examples #' # library(paletteer) #' @@ -235,7 +235,9 @@ data_color <- function(data, data } -# Apply color scale styles to the gt table data +#' Apply color scale styles to the gt table data +#' +#' @noRd scale_apply_styles <- function(data, column, styles, @@ -278,17 +280,17 @@ scale_apply_styles <- function(data, #' apply greater darkening or lightening for those colors in the midrange #' compared to any very dark or very light colors in the input palette. #' -#' This function can be useful when combined with the \code{\link{data_color}()} -#' function's \code{palette} argument, which can use a vector of colors or any -#' of the \code{col_*} functions from the \pkg{scales} package (all of which -#' have a \code{palette} argument). +#' This function can be useful when combined with the [data_color()] function's +#' `palette` argument, which can use a vector of colors or any of the `col_*` +#' functions from the \pkg{scales} package (all of which have a `palette` +#' argument). #' -#' @param colors a vector of colors that will undergo an adjustment in +#' @param colors A vector of colors that will undergo an adjustment in #' luminance. Each color value provided must either be a color name (in the -#' set of colors provided by \code{grDevices::colors()}) or a hexadecimal -#' string in the form of "#RRGGBB" or "#RRGGBBAA". -#' @param steps a positive or negative factor by which the luminance will be -#' adjusted. Must be a number between \code{-2.0} and \code{2.0}. +#' set of colors provided by `grDevices::colors()`) or a hexadecimal string in +#' the form of "#RRGGBB" or "#RRGGBBAA". +#' @param steps A positive or negative factor by which the luminance will be +#' adjusted. Must be a number between `-2.0` and `2.0`. #' @examples #' # Get a palette of 8 pastel colors from #' # the RColorBrewer package @@ -378,7 +380,9 @@ adjust_luminance <- function(colors, hcl_colors } -# Extract a vector of alpha values for a vector of colors +#' Extract a vector of alpha values for a vector of colors +#' +#' @noRd get_alpha_vec <- function(colors) { alpha <- c() @@ -397,8 +401,8 @@ get_alpha_vec <- function(colors) { alpha } -# Function for determining the best `light` and `dark` colors to appear above a -# background color +#' Determining the best `light` and `dark` colors for contrast +#' #' @importFrom grDevices col2rgb #' @noRd ideal_fgnd_color <- function(bgnd_colors, diff --git a/R/datasets.R b/R/datasets.R index 3b73aa03d2..fddb231077 100644 --- a/R/datasets.R +++ b/R/datasets.R @@ -4,20 +4,19 @@ #' population is based on counts of all residents regardless of legal status or #' citizenship. Country identifiers include the English-language country names, #' and the 2- and 3-letter ISO 3166-1 country codes. Each row contains a -#' \code{population} value for a given \code{year} (from 1960 to 2017). Any -#' \code{NA} values for \code{populations} indicate the non-existence of the -#' country during that year. +#' `population` value for a given `year` (from 1960 to 2017). Any `NA` values +#' for `populations` indicate the non-existence of the country during that year. #' #' @format A tibble with 12470 rows and 5 variables: #' \describe{ -#' \item{country_name}{Name of the country} -#' \item{country_code_2}{The 2-letter ISO 3166-1 country code} -#' \item{country_code_3}{The 3-letter ISO 3166-1 country code} -#' \item{year}{The year for the population estimate} -#' \item{population}{The population estimate, midway through the year} +#' \item{country_name}{Name of the country} +#' \item{country_code_2}{The 2-letter ISO 3166-1 country code} +#' \item{country_code_3}{The 3-letter ISO 3166-1 country code} +#' \item{year}{The year for the population estimate} +#' \item{population}{The population estimate, midway through the year} #' } #' -#' @source \url{https://data.worldbank.org/indicator/SP.POP.TOTL} +#' @source #' #' @examples #' # Here is a glimpse at the data @@ -50,15 +49,15 @@ #' \item{latitude}{The latitude in decimal degrees for the observations} #' \item{month}{The measurement month; all calculations where conducted #' for the first day of each month} -#' \item{tst}{The true solar time at the given \code{latitude} and date -#' (first of \code{month}) for which the solar zenith angle is calculated} -#' \item{sza}{The solar zenith angle in degrees, where \code{NA}s -#' indicate that sunrise hadn't yet occurred by the \code{tst} value} +#' \item{tst}{The true solar time at the given `latitude` and date +#' (first of `month`) for which the solar zenith angle is calculated} +#' \item{sza}{The solar zenith angle in degrees, where `NA`s +#' indicate that sunrise hadn't yet occurred by the `tst` value} #' } #' #' @source Calculated Actinic Fluxes (290 - 700 nm) for Air Pollution #' Photochemistry Applications (Peterson, 1976), available at: -#' \url{https://nepis.epa.gov/Exe/ZyPURL.cgi?Dockey=9100JA26.txt}. +#' . #' #' @examples #' # Here is a glimpse at the data @@ -68,19 +67,19 @@ #' Deluxe automobiles from the 2014-2017 period #' -#' Expensive and fast cars. Not your father's \code{mtcars}. Each row describes -#' a car of a certain make, model, year, and trim. Basic specifications such as +#' Expensive and fast cars. Not your father's `mtcars`. Each row describes a car +#' of a certain make, model, year, and trim. Basic specifications such as #' horsepower, torque, EPA MPG ratings, type of drivetrain, and transmission #' characteristics are provided. The country of origin for the car manufacturer #' is also given. #' -#' All of the \code{gtcars} have something else in common (aside from the high -#' asking prices): they are all grand tourer vehicles. These are proper GT cars -#' that blend pure driving thrills with a level of comfort that is more expected -#' from a fine limousine (e.g., a Rolls-Royce Phantom EWB). You'll find that, -#' with these cars, comfort is emphasized over all-out performance. -#' Nevertheless, the driving experience should also mean motoring at speed, -#' doing so in style and safety. +#' All of the `gtcars` have something else in common (aside from the high asking +#' prices): they are all grand tourer vehicles. These are proper GT cars that +#' blend pure driving thrills with a level of comfort that is more expected from +#' a fine limousine (e.g., a Rolls-Royce Phantom EWB). You'll find that, with +#' these cars, comfort is emphasized over all-out performance. Nevertheless, the +#' driving experience should also mean motoring at speed, doing so in style and +#' safety. #' #' @format A tibble with 47 rows and 15 variables: #' \describe{ @@ -89,23 +88,22 @@ #' \item{year}{The car's model year} #' \item{trim}{A short description of the car model's trim} #' \item{bdy_style}{An identifier of the car's body style, which is either -#' \code{coupe}, \code{convertible}, \code{sedan}, or \code{hatchback}} +#' `coupe`, `convertible`, `sedan`, or `hatchback`} #' \item{hp, hp_rpm}{The car's horsepower and the associated RPM level} #' \item{trq, trq_rpm}{The car's torque and the associated RPM level} #' \item{mpg_c, mpg_h}{The miles per gallon fuel efficiency rating for city #' and highway driving} #' \item{drivetrain}{The car's drivetrain which, for this dataset is either -#' \code{rwd} (Rear Wheel Drive) or \code{awd} (All Wheel Drive)} +#' `rwd` (Rear Wheel Drive) or `awd` (All Wheel Drive)} #' \item{trsmn}{The codified transmission type, where the number part is #' the number of gears; the car could have automatic transmission -#' (\code{a}), manual transmission (\code{m}), an option to switch between -#' both types (\code{am}), or, direct drive (\code{dd})} +#' (`a`), manual transmission (`m`), an option to switch between +#' both types (`am`), or, direct drive (`dd`)} #' \item{ctry_origin}{The country name for where the vehicle manufacturer #' is headquartered} #' } #' -#' @source Various pages within \url{https://www.edmunds.com}. -#' +#' @source Various pages within . #' @examples #' # Here is a glimpse at the data #' # available in `gtcars` @@ -120,15 +118,14 @@ #' #' @format A tibble with 16607 rows and 7 variables: #' \describe{ -#' \item{date}{The date expressed as \code{Date} values} -#' \item{open, high, low, close}{The day's opening, high, low, and closing -#' prices in USD; the \code{close} price is adjusted for splits} -#' \item{volume}{the number of trades for the given \code{date}} -#' \item{adj_close}{The close price adjusted for both dividends and splits} +#' \item{date}{The date expressed as `Date` values} +#' \item{open, high, low, close}{The day's opening, high, low, and closing +#' prices in USD; the `close` price is adjusted for splits} +#' \item{volume}{the number of trades for the given `date`} +#' \item{adj_close}{The close price adjusted for both dividends and splits} #' } #' -#' @source Data collected from \url{https://finance.yahoo.com/quote/\%5EGSPC/history/}. -#' +#' @source Data collected from . #' @examples #' # Here is a glimpse at the data #' # available in `sp500` @@ -140,112 +137,112 @@ #' A synthetic dataset that describes pizza sales for a pizza place somewhere in #' the US. While the contents are artificial, the ingredients used to make the #' pizzas are far from it. There are 32 different pizzas that fall into 4 -#' different categories: \code{classic} (classic pizzas: 'You probably had one -#' like it before, but never like this!'), \code{chicken} (pizzas with chicken -#' as a major ingredient: 'Try the Southwest Chicken Pizza! You'll love it!'), -#' \code{supreme} (pizzas that try a little harder: 'My Soppressata pizza uses -#' only the finest salami from my personal salumist!'), and, \code{veggie} -#' (pizzas without any meats whatsoever: 'My Five Cheese pizza has so many -#' cheeses, I can only offer it in Large Size!'). +#' different categories: `classic` (classic pizzas: 'You probably had one like +#' it before, but never like this!'), `chicken` (pizzas with chicken as a major +#' ingredient: 'Try the Southwest Chicken Pizza! You'll love it!'), `supreme` +#' (pizzas that try a little harder: 'My Soppressata pizza uses only the finest +#' salami from my personal salumist!'), and, `veggie` (pizzas without any meats +#' whatsoever: 'My Five Cheese pizza has so many cheeses, I can only offer it in +#' Large Size!'). #' -#' Each pizza in the dataset is identified by a short \code{name}. The following +#' Each pizza in the dataset is identified by a short `name`. The following #' listings provide the full names of each pizza and their main ingredients. #' #' Classic Pizzas: #' \itemize{ -#' \item \code{classic_dlx}: The Classic Deluxe Pizza (Pepperoni, Mushrooms, Red +#' \item `classic_dlx`: The Classic Deluxe Pizza (Pepperoni, Mushrooms, Red #' Onions, Red Peppers, Bacon) -#' \item \code{big_meat}: The Big Meat Pizza (Bacon, Pepperoni, Italian Sausage, +#' \item `big_meat`: The Big Meat Pizza (Bacon, Pepperoni, Italian Sausage, #' Chorizo Sausage) -#' \item \code{pepperoni}: The Pepperoni Pizza (Mozzarella Cheese, Pepperoni) -#' \item \code{hawaiian}: The Hawaiian Pizza (Sliced Ham, Pineapple, Mozzarella +#' \item `pepperoni`: The Pepperoni Pizza (Mozzarella Cheese, Pepperoni) +#' \item `hawaiian`: The Hawaiian Pizza (Sliced Ham, Pineapple, Mozzarella #' Cheese) -#' \item \code{pep_msh_pep}: The Pepperoni, Mushroom, and Peppers Pizza +#' \item `pep_msh_pep`: The Pepperoni, Mushroom, and Peppers Pizza #' (Pepperoni, Mushrooms, and Green Peppers) -#' \item \code{ital_cpcllo}: The Italian Capocollo Pizza (Capocollo, Red +#' \item `ital_cpcllo`: The Italian Capocollo Pizza (Capocollo, Red #' Peppers, Tomatoes, Goat Cheese, Garlic, Oregano) -#' \item \code{napolitana}: The Napolitana Pizza (Tomatoes, Anchovies, Green +#' \item `napolitana`: The Napolitana Pizza (Tomatoes, Anchovies, Green #' Olives, Red Onions, Garlic) -#' \item \code{the_greek}: The Greek Pizza (Kalamata Olives, Feta Cheese, +#' \item `the_greek`: The Greek Pizza (Kalamata Olives, Feta Cheese, #' Tomatoes, Garlic, Beef Chuck Roast, Red Onions) #' } #' #' Chicken Pizzas: #' \itemize{ -#' \item \code{thai_ckn}: The Thai Chicken Pizza (Chicken, Pineapple, Tomatoes, +#' \item `thai_ckn`: The Thai Chicken Pizza (Chicken, Pineapple, Tomatoes, #' Red Peppers, Thai Sweet Chilli Sauce) -#' \item \code{bbq_ckn}: The Barbecue Chicken Pizza (Barbecued Chicken, Red +#' \item `bbq_ckn`: The Barbecue Chicken Pizza (Barbecued Chicken, Red #' Peppers, Green Peppers, Tomatoes, Red Onions, Barbecue Sauce) -#' \item \code{southw_ckn}: The Southwest Chicken Pizza (Chicken, Tomatoes, Red +#' \item `southw_ckn`: The Southwest Chicken Pizza (Chicken, Tomatoes, Red #' Peppers, Red Onions, Jalapeno Peppers, Corn, Cilantro, Chipotle Sauce) -#' \item \code{cali_ckn}: The California Chicken Pizza (Chicken, Artichoke, +#' \item `cali_ckn`: The California Chicken Pizza (Chicken, Artichoke, #' Spinach, Garlic, Jalapeno Peppers, Fontina Cheese, Gouda Cheese) -#' \item \code{ckn_pesto}: The Chicken Pesto Pizza (Chicken, Tomatoes, Red +#' \item `ckn_pesto`: The Chicken Pesto Pizza (Chicken, Tomatoes, Red #' Peppers, Spinach, Garlic, Pesto Sauce) -#' \item \code{ckn_alfredo}: The Chicken Alfredo Pizza (Chicken, Red Onions, +#' \item `ckn_alfredo`: The Chicken Alfredo Pizza (Chicken, Red Onions, #' Red Peppers, Mushrooms, Asiago Cheese, Alfredo Sauce) #' } #' #' Supreme Pizzas: #' \itemize{ -#' \item \code{brie_carre}: The Brie Carre Pizza (Brie Carre Cheese, Prosciutto, +#' \item `brie_carre`: The Brie Carre Pizza (Brie Carre Cheese, Prosciutto, #' Caramelized Onions, Pears, Thyme, Garlic) -#' \item \code{calabrese}: The Calabrese Pizza (‘Nduja Salami, Pancetta, +#' \item `calabrese`: The Calabrese Pizza (‘Nduja Salami, Pancetta, #' Tomatoes, Red Onions, Friggitello Peppers, Garlic) -#' \item \code{soppressata}: The Soppressata Pizza (Soppressata Salami, Fontina +#' \item `soppressata`: The Soppressata Pizza (Soppressata Salami, Fontina #' Cheese, Mozzarella Cheese, Mushrooms, Garlic) -#' \item \code{sicilian}: The Sicilian Pizza (Coarse Sicilian Salami, Tomatoes, +#' \item `sicilian`: The Sicilian Pizza (Coarse Sicilian Salami, Tomatoes, #' Green Olives, Luganega Sausage, Onions, Garlic) -#' \item \code{ital_supr}: The Italian Supreme Pizza (Calabrese Salami, +#' \item `ital_supr`: The Italian Supreme Pizza (Calabrese Salami, #' Capocollo, Tomatoes, Red Onions, Green Olives, Garlic) -#' \item \code{peppr_salami}: The Pepper Salami Pizza (Genoa Salami, Capocollo, +#' \item `peppr_salami`: The Pepper Salami Pizza (Genoa Salami, Capocollo, #' Pepperoni, Tomatoes, Asiago Cheese, Garlic) -#' \item \code{prsc_argla}: The Prosciutto and Arugula Pizza (Prosciutto di San +#' \item `prsc_argla`: The Prosciutto and Arugula Pizza (Prosciutto di San #' Daniele, Arugula, Mozzarella Cheese) -#' \item \code{spinach_supr}: The Spinach Supreme Pizza (Spinach, Red Onions, +#' \item `spinach_supr`: The Spinach Supreme Pizza (Spinach, Red Onions, #' Pepperoni, Tomatoes, Artichokes, Kalamata Olives, Garlic, Asiago Cheese) -#' \item \code{spicy_ital}: The Spicy Italian Pizza (Capocollo, Tomatoes, Goat +#' \item `spicy_ital`: The Spicy Italian Pizza (Capocollo, Tomatoes, Goat #' Cheese, Artichokes, Peperoncini verdi, Garlic) #' } #' #' Vegetable Pizzas #' \itemize{ -#' \item \code{mexicana}: The Mexicana Pizza (Tomatoes, Red Peppers, Jalapeno +#' \item `mexicana`: The Mexicana Pizza (Tomatoes, Red Peppers, Jalapeno #' Peppers, Red Onions, Cilantro, Corn, Chipotle Sauce, Garlic) -#' \item \code{four_cheese}: The Four Cheese Pizza (Ricotta Cheese, Gorgonzola +#' \item `four_cheese`: The Four Cheese Pizza (Ricotta Cheese, Gorgonzola #' Piccante Cheese, Mozzarella Cheese, Parmigiano Reggiano Cheese, Garlic) -#' \item \code{five_cheese}: The Five Cheese Pizza (Mozzarella Cheese, Provolone +#' \item `five_cheese`: The Five Cheese Pizza (Mozzarella Cheese, Provolone #' Cheese, Smoked Gouda Cheese, Romano Cheese, Blue Cheese, Garlic) -#' \item \code{spin_pesto}: The Spinach Pesto Pizza (Spinach, Artichokes, +#' \item `spin_pesto`: The Spinach Pesto Pizza (Spinach, Artichokes, #' Tomatoes, Sun-dried Tomatoes, Garlic, Pesto Sauce) -#' \item \code{veggie_veg}: The Vegetables + Vegetables Pizza (Mushrooms, +#' \item `veggie_veg`: The Vegetables + Vegetables Pizza (Mushrooms, #' Tomatoes, Red Peppers, Green Peppers, Red Onions, Zucchini, Spinach, Garlic) -#' \item \code{green_garden}: The Green Garden Pizza (Spinach, Mushrooms, +#' \item `green_garden`: The Green Garden Pizza (Spinach, Mushrooms, #' Tomatoes, Green Olives, Feta Cheese) -#' \item \code{mediterraneo}: The Mediterranean Pizza (Spinach, Artichokes, +#' \item `mediterraneo`: The Mediterranean Pizza (Spinach, Artichokes, #' Kalamata Olives, Sun-dried Tomatoes, Feta Cheese, Plum Tomatoes, Red Onions) -#' \item \code{spinach_fet}: The Spinach and Feta Pizza (Spinach, Mushrooms, +#' \item `spinach_fet`: The Spinach and Feta Pizza (Spinach, Mushrooms, #' Red Onions, Feta Cheese, Garlic) -#' \item \code{ital_veggie}: The Italian Vegetables Pizza (Eggplant, Artichokes, +#' \item `ital_veggie`: The Italian Vegetables Pizza (Eggplant, Artichokes, #' Tomatoes, Zucchini, Red Peppers, Garlic, Pesto Sauce) #' } #' #' @format A tibble with 49574 rows and 7 variables: #' \describe{ #' \item{id}{The ID for the order, which consists of one or more pizzas -#' at a give \code{date} and \code{time}} -#' \item{date}{A character representation of the \code{order} date, +#' at a give `date` and `time`} +#' \item{date}{A character representation of the `order` date, #' expressed in the ISO 8601 date format (YYYY-MM-DD)} -#' \item{time}{A character representation of the \code{order} time, +#' \item{time}{A character representation of the `order` time, #' expressed as a 24-hour time the ISO 8601 extended time format #' (hh:mm:ss)} #' \item{name}{The short name for the pizza} -#' \item{size}{The size of the pizza, which can either be \code{S}, -#' \code{M}, \code{L}, \code{XL} (rare!), or \code{XXL} (even rarer!); -#' most pizzas are available in the \code{S}, \code{M}, and \code{L} sizes +#' \item{size}{The size of the pizza, which can either be `S`, +#' `M`, `L`, `XL` (rare!), or `XXL` (even rarer!); +#' most pizzas are available in the `S`, `M`, and `L` sizes #' but exceptions apply} #' \item{type}{The category or type of pizza, which can either be -#' \code{classic}, \code{chicken}, \code{supreme}, or \code{veggie}} +#' `classic`, `chicken`, `supreme`, or `veggie`} #' \item{price}{The price of the pizza and the amount that it sold for #' (in USD)} #' } @@ -261,28 +258,27 @@ #' This tibble contains data of a few different classes, which makes it #' well-suited for quick experimentation with the functions in this package. It #' contains only eight rows with numeric, character, and factor columns. The -#' last 4 rows contain \code{NA} values in the majority of this tibble's columns -#' (1 missing value per column). The \code{date}, \code{time}, and -#' \code{datetime} columns are character-based dates/times in the familiar ISO -#' 8601 format. The \code{row} and \code{group} columns provide for unique -#' rownames and two groups (\code{grp_a} and \code{grp_b}) for experimenting -#' with the \code{\link{gt}()} function's \code{rowname_col} and -#' \code{groupname_col} arguments. +#' last 4 rows contain `NA` values in the majority of this tibble's columns (1 +#' missing value per column). The `date`, `time`, and `datetime` columns are +#' character-based dates/times in the familiar ISO 8601 format. The `row` and +#' `group` columns provide for unique rownames and two groups (`grp_a` and +#' `grp_b`) for experimenting with the [gt()] function's `rowname_col` and +#' `groupname_col` arguments. #' #' @format A tibble with 8 rows and 9 variables: #' \describe{ #' \item{num}{a numeric column ordered with increasingly larger values} -#' \item{char}{a character column composed of names of fruits from \code{a} to -#' \code{h}} +#' \item{char}{a character column composed of names of fruits from `a` to +#' `h`} #' \item{fctr}{a factor column with numbers from 1 to 8, written out} #' \item{date, time, datetime}{character columns with dates, times, and #' datetimes} #' \item{currency}{a numeric column that is useful for testing currency-based #' formatting} -#' \item{row}{a character column in the format \code{row_X} which can be +#' \item{row}{a character column in the format `row_X` which can be #' useful for testing with row captions in a table stub} -#' \item{group}{a character column with four \code{grp_a} values and four -#' \code{grp_b} values which can be useful for testing tables that contain +#' \item{group}{a character column with four `grp_a` values and four +#' `grp_b` values which can be useful for testing tables that contain #' row groups} #' } #' diff --git a/R/extract_summary.R b/R/extract_summary.R index 53af783603..e4a2ddd96b 100644 --- a/R/extract_summary.R +++ b/R/extract_summary.R @@ -1,10 +1,10 @@ #' Extract a summary list from a \pkg{gt} object #' -#' Get a list of summary row data frames from a \code{gt_tbl} object where -#' summary rows were added via the \code{\link{summary_rows}()} function. The -#' output data frames contain the \code{groupname} and \code{rowname} columns, -#' whereby \code{rowname} contains descriptive stub labels for the summary rows. -#' @param data a table object that is created using the \code{\link{gt}()} +#' Get a list of summary row data frames from a `gt_tbl` object where +#' summary rows were added via the [summary_rows()] function. The +#' output data frames contain the `groupname` and `rowname` columns, +#' whereby `rowname` contains descriptive stub labels for the summary rows. +#' @param data a table object that is created using the [gt()] #' function. #' @return a list of data frames containing summary data. #' @examples diff --git a/R/format_data.R b/R/format_data.R index 828388f595..36ad3365c8 100644 --- a/R/format_data.R +++ b/R/format_data.R @@ -18,71 +18,64 @@ #' formatting specific to the chosen locale #' } #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. -#' -#' @param data A table object that is created using the \code{\link{gt}()} -#' function. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. +#' +#' @param data A table object that is created using the [gt()] function. #' @param columns The columns to format. Can either be a series of column names -#' provided in \code{vars()}, a vector of column indices, or a helper function -#' focused on selections. The select helper functions are: -#' \code{\link{starts_with}()}, \code{\link{ends_with}()}, -#' \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -#' and \code{\link{everything}()}. +#' provided in [vars()], a vector of column indices, or a helper function +#' focused on selections. The select helper functions are: [starts_with()], +#' [ends_with()], [contains()], [matches()], [one_of()], and [everything()]. #' @param rows Optional rows to format. Not providing any value results in all -#' rows in \code{columns} being formatted. Can either be a vector of row -#' captions provided \code{c()}, a vector of row indices, or a helper function -#' focused on selections. The select helper functions are: -#' \code{\link{starts_with}()}, \code{\link{ends_with}()}, -#' \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -#' and \code{\link{everything}()}. We can also use expressions to filter down -#' to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}). +#' rows in `columns` being formatted. Can either be a vector of row captions +#' provided [c()], a vector of row indices, or a helper function focused on +#' selections. The select helper functions are: [starts_with()], +#' [ends_with()], [contains()], [matches()], [one_of()], and [everything()]. +#' We can also use expressions to filter down to the rows we need (e.g., +#' `[colname_1] > 100 & [colname_2] < 50`). #' @param decimals An option to specify the exact number of decimal places to -#' use. The default number of decimal places is \code{2}. +#' use. The default number of decimal places is `2`. #' @param drop_trailing_zeros A logical value that allows for removal of #' trailing zeros (those redundant zeros after the decimal mark). #' @param use_seps An option to use digit group separators. The type of digit -#' group separator is set by \code{sep_mark} and overridden if a locale ID is -#' provided to \code{locale}. This setting is \code{TRUE} by default. -#' @param scale_by A value to scale the input. The default is \code{1.0}. All -#' numeric values will be multiplied by this value first before undergoing -#' formatting. This value will be ignored if using any of the \code{suffixing} -#' options (i.e., where \code{suffixing} is not set to \code{FALSE}). +#' group separator is set by `sep_mark` and overridden if a locale ID is +#' provided to `locale`. This setting is `TRUE` by default. +#' @param scale_by A value to scale the input. The default is `1.0`. All numeric +#' values will be multiplied by this value first before undergoing formatting. +#' This value will be ignored if using any of the `suffixing` options (i.e., +#' where `suffixing` is not set to `FALSE`). #' @param suffixing An option to scale and apply suffixes to larger numbers -#' (e.g., \code{1924000} can be transformed to \code{1.92M}). This option can -#' accept a logical value, where \code{FALSE} (the default) will not perform -#' this transformation and \code{TRUE} will apply thousands (\code{K}), -#' millions (\code{M}), billions (\code{B}), and trillions (\code{T}) suffixes -#' after automatic value scaling. We can also specify which symbols to use for -#' each of the value ranges by using a character vector of the preferred -#' symbols to replace the defaults (e.g., \code{c("k", "Ml", "Bn", "Tr")}). -#' Including \code{NA} values in the vector will ensure that the particular -#' range will either not be included in the transformation (e.g, \code{c(NA, -#' "M", "B", "T")} won't modify numbers in the thousands range) or the range -#' will inherit a previous suffix (e.g., with \code{c("K", "M", NA, "T")}, all -#' numbers in the range of millions and billions will be in terms of -#' millions). Any use of \code{suffixing} (where not \code{FALSE}) means that -#' any value provided to \code{scale_by} will be ignored. +#' (e.g., `1924000` can be transformed to `1.92M`). This option can accept a +#' logical value, where `FALSE` (the default) will not perform this +#' transformation and `TRUE` will apply thousands (`K`), millions (`M`), +#' billions (`B`), and trillions (`T`) suffixes after automatic value scaling. +#' We can also specify which symbols to use for each of the value ranges by +#' using a character vector of the preferred symbols to replace the defaults +#' (e.g., `c("k", "Ml", "Bn", "Tr")`). Including `NA` values in the vector +#' will ensure that the particular range will either not be included in the +#' transformation (e.g, `c(NA, "M", "B", "T")` won't modify numbers in the +#' thousands range) or the range will inherit a previous suffix (e.g., with +#' `c("K", "M", NA, "T")`, all numbers in the range of millions and billions +#' will be in terms of millions). Any use of `suffixing` (where not `FALSE`) +#' means that any value provided to `scale_by` will be ignored. #' @param pattern A formatting pattern that allows for decoration of the -#' formatted value. The value itself is represented by \code{{x}} and all -#' other characters are taken to be string literals. +#' formatted value. The value itself is represented by `{x}` and all other +#' characters are taken to be string literals. #' @param sep_mark The mark to use as a separator between groups of digits -#' (e.g., using \code{sep_mark = ","} with \code{1000} would result in a -#' formatted value of \code{1,000}). -#' @param dec_mark The character to use as a decimal mark (e.g., using -#' \code{dec_mark = ","} with \code{0.152} would result in a formatted value -#' of \code{0,152}). +#' (e.g., using `sep_mark = ","` with `1000` would result in a formatted value +#' of `1,000`). +#' @param dec_mark The character to use as a decimal mark (e.g., using `dec_mark +#' = ","` with `0.152` would result in a formatted value of `0,152`). #' @param locale An optional locale ID that can be used for formatting the value -#' according the locale's rules. Examples include \code{"en_US"} for English -#' (United States) and \code{"fr_FR"} for French (France). The use of a valid -#' locale ID will override any values provided in \code{sep_mark} and -#' \code{dec_mark}. We can use the \code{\link{info_locales}()} function as a -#' useful reference for all of the locales that are supported. -#' @return An object of class \code{gt_tbl}. +#' according the locale's rules. Examples include `"en_US"` for English +#' (United States) and `"fr_FR"` for French (France). The use of a valid +#' locale ID will override any values provided in `sep_mark` and `dec_mark`. +#' We can use the [info_locales()] function as a useful reference for all of +#' the locales that are supported. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # format the `num` column as numeric @@ -200,15 +193,14 @@ fmt_number <- function(data, #' formatting specific to the chosen locale #' } #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # format the `num` column as partially @@ -332,7 +324,7 @@ fmt_scientific <- function(data, #' #' @inheritParams fmt_number #' @inheritParams fmt_currency -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @noRd fmt_symbol <- function(data, columns, @@ -438,9 +430,9 @@ fmt_symbol <- function(data, #' #' With numeric values in a \pkg{gt} table, we can perform percentage-based #' formatting. It is assumed the input numeric values are in a fractional format -#' since the numbers will be automatically multiplied by \code{100} before -#' decorating with a percent sign. For more control over percentage formatting, -#' we can use the following options: +#' since the numbers will be automatically multiplied by `100` before decorating +#' with a percent sign. For more control over percentage formatting, we can use +#' the following options: #' \itemize{ #' \item percent sign placement: the percent sign can be placed after or #' before the values and a space can be inserted between the symbol and the @@ -455,19 +447,18 @@ fmt_symbol <- function(data, #' formatting specific to the chosen locale #' } #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number #' @param incl_space An option for whether to include a space between the value #' and the percent sign. The default is to not introduce a space character. #' @param placement The placement of the percent sign. This can be either be -#' \code{right} (the default) or \code{left}. -#' @return an object of class \code{gt_tbl}. +#' `right` (the default) or `left`. +#' @return an object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # format the `num` column to have @@ -554,38 +545,35 @@ fmt_percent <- function(data, #' currency formatting specific to the chosen locale #' } #' -#' We can use the \code{\link{info_currencies}()} function for a useful -#' reference on all of the possible inputs to \code{currency}. +#' We can use the [info_currencies()] function for a useful reference on all of +#' the possible inputs to the `currency` argument. #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number #' @param currency The currency to use for the numeric value. This input can be -#' supplied as a 3-letter currency code (e.g., \code{"USD"} for U.S. Dollars, -#' \code{"EUR"} for the Euro currency). Use \code{\link{info_currencies}()} to -#' get an information table with all of the valid currency codes and examples -#' of each. Alternatively, we can provide a common currency name (e.g., -#' \code{"dollar"}, \code{"pound"}, \code{"yen"}, etc.) to simplify the -#' process. Use \code{\link{info_currencies}()} with the \code{type == -#' "symbol"} option to view an information table with all of the supported -#' currency symbol names along with examples. If nothing is provided then -#' \code{"USD"} will be used. +#' supplied as a 3-letter currency code (e.g., `"USD"` for U.S. Dollars, +#' `"EUR"` for the Euro currency). Use [info_currencies()] to get an +#' information table with all of the valid currency codes and examples of +#' each. Alternatively, we can provide a common currency name (e.g., +#' `"dollar"`, `"pound"`, `"yen"`, etc.) to simplify the process. Use +#' [info_currencies()] with the `type == "symbol"` option to view an +#' information table with all of the supported currency symbol names along +#' with examples. If nothing is provided then `"USD"` will be used. #' @param use_subunits An option for whether the subunits portion of a currency #' value should be displayed. #' @param accounting An option to use accounting style for currency values. With -#' \code{FALSE} (the default), negative values will be shown with a negative -#' sign. Using \code{accounting = TRUE} will put negative values in -#' parentheses. +#' `FALSE` (the default), negative values will be shown with a minus sign. +#' Using `accounting = TRUE` will put negative values in parentheses. #' @param placement The placement of the currency symbol. This can be either be -#' \code{left} (the default) or \code{right}. +#' `left` (the default) or `right`. #' @param incl_space An option for whether to include a space between the value #' and the currency symbol. The default is to not introduce a space character. -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # format the `currency` column to have @@ -672,49 +660,46 @@ fmt_currency <- function(data, #' Format values as dates #' -#' Format input date values that are either of the \code{Date} type, or, are +#' Format input date values that are either of the `Date` type, or, are #' character-based and expressed according to the ISO 8601 date format -#' (\code{YYYY-MM-DD}). Once the appropriate data cells are targeted with -#' \code{columns} (and, optionally, \code{rows}), we can simply apply a preset -#' date style (see table in \code{\link{info_date_style}()} for info) to format -#' the dates. +#' (`YYYY-MM-DD`). Once the appropriate data cells are targeted with `columns` +#' (and, optionally, `rows`), we can simply apply a preset date style (see table +#' in [info_date_style()] for info) to format the dates. #' #' The following date styles are available for simpler formatting of ISO dates -#' (all using the input date of \code{2000-02-29} in the example output dates): +#' (all using the input date of `2000-02-29` in the example output dates): #' #' \enumerate{ -#' \item iso: \code{2000-02-29} -#' \item wday_month_day_year: \code{Tuesday, February 29, 2000} -#' \item wd_m_day_year: \code{Tue, Feb 29, 2000} -#' \item wday_day_month_year: \code{Tuesday 29 February 2000} -#' \item month_day_year: \code{February 29, 2000} -#' \item m_day_year: \code{Feb 29, 2000} -#' \item day_m_year: \code{29 Feb 2000} -#' \item day_month_year: \code{29 February 2000} -#' \item day_month: \code{29 February} -#' \item year: \code{2000} -#' \item month: \code{February} -#' \item day: \code{29} -#' \item year.mn.day: \code{2000/02/29} -#' \item y.mn.day: \code{0/02/29} +#' \item iso: `2000-02-29` +#' \item wday_month_day_year: `Tuesday, February 29, 2000` +#' \item wd_m_day_year: `Tue, Feb 29, 2000` +#' \item wday_day_month_year: `Tuesday 29 February 2000` +#' \item month_day_year: `February 29, 2000` +#' \item m_day_year: `Feb 29, 2000` +#' \item day_m_year: `29 Feb 2000` +#' \item day_month_year: `29 February 2000` +#' \item day_month: `29 February` +#' \item year: `2000` +#' \item month: `February` +#' \item day: `29` +#' \item year.mn.day: `2000/02/29` +#' \item y.mn.day: `0/02/29` #' } #' -#' We can use the \code{\link{info_date_style}()} function for a useful -#' reference on all of the possible inputs to \code{date_style}. +#' We can use the [info_date_style()] function for a useful reference on all of +#' the possible inputs to `date_style`. #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @param date_style The date style to use. Supply a number (from \code{1} to -#' \code{14}) that corresponds to the preferred date style. Use -#' \code{\link{info_date_style}()} to see the different numbered and named date -#' presets. -#' @return An object of class \code{gt_tbl}. +#' @param date_style The date style to use. Supply a number (from `1` to `14`) +#' that corresponds to the preferred date style. Use [info_date_style()] to +#' see the different numbered and named date presets. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `date` and `time` columns; @@ -798,38 +783,36 @@ fmt_date <- function(data, #' Format values as times #' #' Format input time values that are character-based and expressed according to -#' the ISO 8601 time format (\code{HH:MM:SS}). Once the appropriate data cells -#' are targeted with \code{columns} (and, optionally, \code{rows}), we can -#' simply apply a preset time style (see table in -#' \code{\link{info_time_style}()} for info) to format the times. +#' the ISO 8601 time format (`HH:MM:SS`). Once the appropriate data cells are +#' targeted with `columns` (and, optionally, `rows`), we can simply apply a +#' preset time style (see table in [info_time_style()] for info) to format the +#' times. #' #' The following time styles are available for simpler formatting of ISO times -#' (all using the input time of \code{14:35:00} in the example output times): +#' (all using the input time of `14:35:00` in the example output times): #' #' \enumerate{ -#' \item hms: \code{14:35:00} -#' \item hm: \code{14:35} -#' \item hms_p: \code{2:35:00 PM} -#' \item hm_p: \code{2:35 PM} -#' \item h_p: \code{2 PM} +#' \item hms: `14:35:00` +#' \item hm: `14:35` +#' \item hms_p: `2:35:00 PM` +#' \item hm_p: `2:35 PM` +#' \item h_p: `2 PM` #' } #' -#' We can use the \code{\link{info_time_style}()} function for a useful -#' reference on all of the possible inputs to \code{time_style}. +#' We can use the [info_time_style()] function for a useful reference on all of +#' the possible inputs to `time_style`. #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @param time_style The time style to use. Supply a number (from \code{1} to -#' \code{5}) that corresponds to the preferred time style. Use -#' \code{\link{info_time_style}()} to see the different numbered and named time -#' presets. -#' @return An object of class \code{gt_tbl}. +#' @param time_style The time style to use. Supply a number (from `1` to `5`) +#' that corresponds to the preferred time style. Use [info_time_style()] to +#' see the different numbered and named time presets. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `date` and `time` columns; @@ -907,60 +890,58 @@ fmt_time <- function(data, #' Format values as date-times #' #' Format input date-time values that are character-based and expressed -#' according to the ISO 8601 date-time format (\code{YYYY-MM-DD HH:MM:SS}). Once -#' the appropriate data cells are targeted with \code{columns} (and, optionally, -#' \code{rows}), we can simply apply preset date and time styles (see tables in -#' \code{\link{info_date_style}()} and \code{\link{info_time_style}()} for more -#' info) to format the data-time values. +#' according to the ISO 8601 date-time format (`YYYY-MM-DD HH:MM:SS`). Once the +#' appropriate data cells are targeted with `columns` (and, optionally, `rows`), +#' we can simply apply preset date and time styles (see tables in +#' [info_date_style()] and [info_time_style()] for more info) to format the +#' data-time values. #' #' The following date styles are available for simpler formatting of the date -#' portion (all using the input date of \code{2000-02-29} in the example output +#' portion (all using the input date of `2000-02-29` in the example output #' dates): #' #' \enumerate{ -#' \item iso: \code{2000-02-29} -#' \item wday_month_day_year: \code{Tuesday, February 29, 2000} -#' \item wd_m_day_year: \code{Tue, Feb 29, 2000} -#' \item wday_day_month_year: \code{Tuesday 29 February 2000} -#' \item month_day_year: \code{February 29, 2000} -#' \item m_day_year: \code{Feb 29, 2000} -#' \item day_m_year: \code{29 Feb 2000} -#' \item day_month_year: \code{29 February 2000} -#' \item day_month: \code{29 February} -#' \item year: \code{2000} -#' \item month: \code{February} -#' \item day: \code{29} -#' \item year.mn.day: \code{2000/02/29} -#' \item y.mn.day: \code{0/02/29} +#' \item iso: `2000-02-29` +#' \item wday_month_day_year: `Tuesday, February 29, 2000` +#' \item wd_m_day_year: `Tue, Feb 29, 2000` +#' \item wday_day_month_year: `Tuesday 29 February 2000` +#' \item month_day_year: `February 29, 2000` +#' \item m_day_year: `Feb 29, 2000` +#' \item day_m_year: `29 Feb 2000` +#' \item day_month_year: `29 February 2000` +#' \item day_month: `29 February` +#' \item year: `2000` +#' \item month: `February` +#' \item day: `29` +#' \item year.mn.day: `2000/02/29` +#' \item y.mn.day: `0/02/29` #' } #' #' The following time styles are available for simpler formatting of the time -#' portion (all using the input time of \code{14:35:00} in the example output -#' times): +#' portion (all using the input time of `14:35:00` in the example output times): #' #' \enumerate{ -#' \item hms: \code{14:35:00} -#' \item hm: \code{14:35} -#' \item hms_p: \code{2:35:00 PM} -#' \item hm_p: \code{2:35 PM} -#' \item h_p: \code{2 PM} +#' \item hms: `14:35:00` +#' \item hm: `14:35` +#' \item hms_p: `2:35:00 PM` +#' \item hm_p: `2:35 PM` +#' \item h_p: `2 PM` #' } #' -#' We can use the \code{\link{info_date_style}()} and -#' \code{\link{info_time_style}()} functions as useful references for all of the -#' possible inputs to \code{date_style} and \code{time_style}. +#' We can use the [info_date_style()] and [info_time_style()] functions as +#' useful references for all of the possible inputs to `date_style` and +#' `time_style`. #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number #' @inheritParams fmt_date #' @inheritParams fmt_time -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `datetime` column; @@ -1023,17 +1004,16 @@ fmt_datetime <- function(data, #' Format Markdown text #' #' Any Markdown-formatted text in the incoming cells will be transformed to the -#' appropriate output type during render when using \code{fmt_markdown()}. +#' appropriate output type during render when using `fmt_markdown()`. #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Create a few Markdown-based #' # text snippets @@ -1119,29 +1099,26 @@ fmt_markdown <- function(data, #' Format by simply passing data through #' #' Format by passing data through no other transformation other than: (1) -#' coercing to \code{character} (as all the \code{fmt_*()} functions do), and -#' (2) applying prefixed or suffixed text via the \code{pattern} argument (the -#' default is to apply nothing). All of this is useful when don't want to modify -#' the input data other than to decorate it within a pattern. Also, this -#' function is useful when used as a \code{formatter} function in the -#' \code{summary_rows} function, where the output may be text or useful as is -#' (that function requires a formatter function). -#' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' coercing to `character` (as all the `fmt_*()` functions do), and (2) applying +#' text via the `pattern` argument (the default is to apply nothing). All of +#' this is useful when don't want to modify the input data other than to +#' decorate it within a pattern. Also, this function is useful when used as the +#' `formatter` function in the [summary_rows()] function, where the output may +#' be text or useful as is. +#' +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number #' @param escape An option to escape text according to the final output format #' of the table. For example, if a LaTeX table is to be generated then LaTeX #' escaping would be performed during rendering. By default this is set to -#' \code{TRUE} and setting to \code{FALSE} is useful in the case where -#' LaTeX-formatted text should be passed through to the output LaTeX table -#' unchanged. -#' @return An object of class \code{gt_tbl}. +#' `TRUE` and setting to `FALSE` is useful in the case where LaTeX-formatted +#' text should be passed through to the output LaTeX table unchanged. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # keep only the `char` column; @@ -1238,22 +1215,21 @@ fmt_passthrough <- function(data, #' Format missing values #' -#' Wherever there is missing data (i.e., \code{NA} values) a customizable mark -#' may present better than the standard \code{NA} text that would otherwise -#' appear. The \code{fmt_missing()} function allows for this replacement through -#' its \code{missing_text} argument (where an em dash serves as the default). +#' Wherever there is missing data (i.e., `NA` values) a customizable mark may +#' present better than the standard `NA` text that would otherwise appear. The +#' `fmt_missing()` function allows for this replacement through its +#' `missing_text` argument (where an em dash serves as the default). #' -#' Targeting of values is done through \code{columns} and additionally by -#' \code{rows} (if nothing is provided for \code{rows} then entire columns are -#' selected). A number of helper functions exist to make targeting more -#' effective. Conditional formatting is possible by providing a conditional -#' expression to the \code{rows} argument. See the Arguments section for more -#' information on this. +#' Targeting of values is done through `columns` and additionally by `rows` (if +#' nothing is provided for `rows` then entire columns are selected). A number of +#' helper functions exist to make targeting more effective. Conditional +#' formatting is possible by providing a conditional expression to the `rows` +#' argument. See the Arguments section for more information on this. #' #' @inheritParams fmt_number -#' @param missing_text The text to be used in place of \code{NA} values in the -#' rendered table. -#' @return An object of class \code{gt_tbl}. +#' @param missing_text The text to be used in place of `NA` values in the +#' rendered table. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # NA values in different columns will @@ -1321,35 +1297,34 @@ fmt_missing <- function(data, #' Set a column format with a formatter function #' -#' The \code{fmt()} function provides greater control in formatting raw data -#' values than any of the specialized \code{fmt_*()} functions that are -#' available in \pkg{gt}. Along with the \code{columns} and \code{rows} -#' arguments that provide some precision in targeting data cells, the \code{fns} -#' argument allows you to define one or more functions for manipulating the raw -#' data. -#' -#' If providing a single function to \code{fns}, the recommended format is in -#' the form: \code{fns = function(x) ...}. This single function will format the -#' targeted data cells the same way regardless of the output format (e.g., HTML, -#' LaTeX, RTF). -#' -#' If you require formatting of \code{x} that depends on the output format, a -#' list of functions can be provided for the \code{html}, \code{latex}, and -#' \code{default} contexts. This can be in the form of \code{fns = list(html = -#' function(x) ..., latex = function(x) ..., default = function(x) ...)}. In -#' this multiple-function case, we recommended including the \code{default} -#' function as a fallback if all contexts aren't provided. -#' -#' As with all of the \code{fmt_*()} functions, targeting of values is done -#' through \code{columns} and additionally by \code{rows} (if nothing is -#' provided for \code{rows} then entire columns are selected). A number of -#' helper functions exist to make targeting more effective. Conditional -#' formatting is possible by providing a conditional expression to the -#' \code{rows} argument. See the Arguments section for more information on this. +#' The `fmt()` function provides greater control in formatting raw data values +#' than any of the specialized `fmt_*()` functions that are available in +#' \pkg{gt}. Along with the `columns` and `rows` arguments that provide some +#' precision in targeting data cells, the `fns` argument allows you to define +#' one or more functions for manipulating the raw data. +#' +#' If providing a single function to `fns`, the recommended format is in the +#' form: `fns = function(x) ...`. This single function will format the targeted +#' data cells the same way regardless of the output format (e.g., HTML, LaTeX, +#' RTF). +#' +#' If you require formatting of `x` that depends on the output format, a list of +#' functions can be provided for the `html`, `latex`, and `default` contexts. +#' This can be in the form of `fns = list(html = function(x) ..., latex = +#' function(x) ..., default = function(x) ...)`. In this multiple-function case, +#' we recommended including the `default` function as a fallback if all contexts +#' aren't provided. +#' +#' As with all of the `fmt_*()` functions, targeting of values is done through +#' `columns` and additionally by `rows` (if nothing is provided for `rows` then +#' entire columns are selected). A number of helper functions exist to make +#' targeting more effective. Conditional formatting is possible by providing a +#' conditional expression to the `rows` argument. See the Arguments section for +#' more information on this. #' #' @inheritParams fmt_number #' @param fns Either a single formatting function or a named list of functions. -#' @return An object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # format the numeric values in the `num` diff --git a/R/gt.R b/R/gt.R index 177b86c44f..990bea060e 100644 --- a/R/gt.R +++ b/R/gt.R @@ -1,37 +1,36 @@ #' Create a \pkg{gt} table object #' -#' The \code{gt()} function creates a \pkg{gt} table object when provided with -#' table data. Using this function is the first step in a typical \pkg{gt} -#' workflow. Once we have the \pkg{gt} table object, we can perform styling +#' The `gt()` function creates a \pkg{gt} table object when provided with table +#' data. Using this function is the first step in a typical \pkg{gt} workflow. +#' Once we have the \pkg{gt} table object, we can perform styling #' transformations before rendering to a display table of various formats (e.g., #' HTML, LaTeX, RTF). #' #' There are a few data ingest options we can consider at this stage. We can -#' choose to create a table stub with rowname captions using the -#' \code{rowname_col} argument. Further to this, stub row groups can be created -#' with the \code{groupname_col}. Both arguments take the name of a column in -#' the input table data. Typically, the data in the \code{groupname_col} will -#' consist of categories of data in a table and the data in the -#' \code{rowname_col} are unique labels (perhaps unique across the entire table -#' or unique within groups). +#' choose to create a table stub with rowname captions using the `rowname_col` +#' argument. Further to this, stub row groups can be created with the +#' `groupname_col`. Both arguments take the name of a column in the input table +#' data. Typically, the data in the `groupname_col` will consist of categories +#' of data in a table and the data in the `rowname_col` are unique labels +#' (perhaps unique across the entire table or unique within groups). #' -#' Row groups can also be created by passing a \code{grouped_df} to \code{gt()} -#' by using the \code{dplyr::group_by()} function on the table data. In this -#' way, two or more columns of categorical data can be used to make row groups. -#' The \code{stub_group.sep} argument allows for control in how the row group -#' label will appear in the display table. +#' Row groups can also be created by passing a `grouped_df` to `gt()` by using +#' the `dplyr::group_by()` function on the table data. In this way, two or more +#' columns of categorical data can be used to make row groups. The +#' `stub_group.sep` argument allows for control in how the row group label will +#' appear in the display table. #' -#' @param data a \code{data.frame} object or a tibble. -#' @param rowname_col the column name in the input \code{data} table to use as -#' row captions to be placed in the display table stub. -#' @param groupname_col the column name in the input \code{data} table to use as +#' @param data A `data.frame` object or a tibble. +#' @param rowname_col The column name in the input `data` table to use as row +#' captions to be placed in the display table stub. +#' @param groupname_col The column name in the input `data` table to use as #' group labels for generation of stub row groups. -#' @param rownames_to_stub an option to take rownames from the input \code{data} +#' @param rownames_to_stub An option to take rownames from the input `data` #' table as row captions in the display table stub. -#' @param stub_group.sep the separator to use between consecutive group names (a -#' possibility when providing \code{data} as a \code{grouped_df} with multiple -#' groups) in the displayed stub row group label. -#' @return an object of class \code{gt_tbl}. +#' @param stub_group.sep The separator to use between consecutive group names (a +#' possibility when providing `data` as a `grouped_df` with multiple groups) +#' in the displayed stub row group label. +#' @return An object of class `gt_tbl`. #' @examples #' # Create a table object using the #' # `exibble` dataset; use the `row` diff --git a/R/gt_preview.R b/R/gt_preview.R index 89562be090..fc2b8de09c 100644 --- a/R/gt_preview.R +++ b/R/gt_preview.R @@ -1,30 +1,28 @@ #' Preview a \pkg{gt} table object #' #' Sometimes you may want to see just a small portion of your input data. We can -#' use \code{gt_preview()} in place of \code{\link{gt}()} to get the first x -#' rows of data and the last y rows of data (which can be set by the -#' \code{top_n} and \code{bottom_n} arguments). It's not advised to use -#' additional \pkg{gt} API functions to further modify the output of -#' \code{gt_preview()}. Furthermore, you cannot pass a \pkg{gt} object to -#' \code{gt_preview()}. +#' use `gt_preview()` in place of [gt()] to get the first x rows of data and the +#' last y rows of data (which can be set by the `top_n` and `bottom_n` +#' arguments). It's not advised to use additional \pkg{gt} API functions to +#' further modify the output of `gt_preview()`. Furthermore, you cannot pass a +#' \pkg{gt} object to `gt_preview()`. #' -#' Any grouped data or magic columns such as \code{rowname} and \code{groupname} -#' will be ignored by \code{gt_preview()} and, as such, one cannot add a stub or -#' group rows in the output table. By default, the output table will include row -#' numbers in a stub (including a range of row numbers for the omitted rows). -#' This row numbering option can be deactivated by setting \code{incl_rownums} -#' to \code{FALSE}. +#' Any grouped data or magic columns such as `rowname` and `groupname` will be +#' ignored by `gt_preview()` and, as such, one cannot add a stub or group rows +#' in the output table. By default, the output table will include row numbers in +#' a stub (including a range of row numbers for the omitted rows). This row +#' numbering option can be deactivated by setting `incl_rownums` to `FALSE`. #' -#' @param data a \code{data.frame} object or a tibble. -#' @param top_n this value will be used as the number of rows from the top of -#' the table to display. The default, \code{5}, will show the first five rows -#' of the table. -#' @param bottom_n the value will be used as the number of rows from the bottom -#' of the table to display. The default, \code{1}, will show the final row of +#' @param data A `data.frame` object or a tibble. +#' @param top_n This value will be used as the number of rows from the top of +#' the table to display. The default, `5`, will show the first five rows of #' the table. -#' @param incl_rownums an option to include the row numbers for \code{data} in -#' the table stub. By default, this is \code{TRUE}. -#' @return an object of class \code{gt_tbl}. +#' @param bottom_n The value will be used as the number of rows from the bottom +#' of the table to display. The default, `1`, will show the final row of the +#' table. +#' @param incl_rownums An option to include the row numbers for `data` in the +#' table stub. By default, this is `TRUE`. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table #' # preview (with only a few of its diff --git a/R/gtsave.R b/R/gtsave.R index 0272c06271..2b065ab877 100644 --- a/R/gtsave.R +++ b/R/gtsave.R @@ -1,27 +1,26 @@ #' Save a \pkg{gt} table as a file #' -#' The \code{gtsave()} function makes it easy to save a \pkg{gt} table to a -#' file. The function guesses the file type by the extension provided in the -#' output filename, producing either an HTML, LaTeX, or RTF file. +#' The `gtsave()` function makes it easy to save a \pkg{gt} table to a file. The +#' function guesses the file type by the extension provided in the output +#' filename, producing either an HTML, LaTeX, or RTF file. #' -#' Output filenames with either the \code{.html} or \code{.htm} extensions will -#' produce an HTML document. In this case, we can pass a \code{TRUE} or -#' \code{FALSE} value to the \code{inline_css} option to obtain an HTML document -#' with inlined CSS styles (the default is \code{FALSE}). More details on CSS -#' inlining are available at \code{\link{as_raw_html}()}. +#' Output filenames with either the `.html` or `.htm` extensions will produce an +#' HTML document. In this case, we can pass a `TRUE` or `FALSE` value to the +#' `inline_css` option to obtain an HTML document with inlined CSS styles (the +#' default is `FALSE`). More details on CSS inlining are available at +#' [as_raw_html()]. #' -#' If the output filename is either of \code{.tex}, \code{.ltx}, or \code{.rnw}, -#' a LaTeX document is produced. An output filename of \code{.rtf} will generate -#' an RTF document. The LaTeX and RTF saving function don't have any options to -#' pass to \code{...}. +#' If the output filename is either of `.tex`, `.ltx`, or `.rnw`, a LaTeX +#' document is produced. An output filename of `.rtf` will generate an RTF +#' document. The LaTeX and RTF saving function don't have any options to pass to +#' `...`. #' -#' @param data a table object that is created using the \code{\link{gt}()} -#' function. -#' @param filename the file name to create on disk. Ensure that an extension -#' compatible with the output types is provided (\code{.html}, \code{.tex}, -#' \code{.ltx}, \code{.rtf}). If a custom save function is provided then the -#' file extension is disregarded. -#' @param ... all other options passed to the appropriate internal saving +#' @param data A table object that is created using the [gt()] function. +#' @param filename The file name to create on disk. Ensure that an extension +#' compatible with the output types is provided (`.html`, `.tex`, `.ltx`, +#' `.rtf`). If a custom save function is provided then the file extension is +#' disregarded. +#' @param ... All other options passed to the appropriate internal saving #' function. #' @export gtsave <- function(data, filename, ...) { @@ -58,7 +57,8 @@ gtsave <- function(data, filename, ...) { ) } -# Saving function for an HTML file +#' Saving function for an HTML file +#' #' @importFrom htmltools as.tags save_html HTML #' @noRd gt_save_html <- function(data, filename, ..., inline_css = FALSE) { @@ -78,7 +78,9 @@ gt_save_html <- function(data, filename, ..., inline_css = FALSE) { } } -# Saving function for a LaTeX file +#' Saving function for a LaTeX file +#' +#' @noRd gt_save_latex <- function(data, filename, ...) { data %>% @@ -86,7 +88,9 @@ gt_save_latex <- function(data, filename, ...) { writeLines(con = filename) } -# Saving function for an RTF file +#' Saving function for an RTF file +#' +#' @noRd gt_save_rtf <- function(data, filename, ...) { data %>% @@ -94,6 +98,8 @@ gt_save_rtf <- function(data, filename, ...) { writeLines(con = filename) } +#' Get the file extension from an input filename +#' #' @importFrom tools file_ext #' @noRd gtsave_file_ext <- function(filename) { diff --git a/R/helpers.R b/R/helpers.R index b6fbfbf271..4e08cf773a 100644 --- a/R/helpers.R +++ b/R/helpers.R @@ -2,42 +2,41 @@ #' #' These helper functions are used to target individual cells in different #' locations (e.g., the stub, the column labels, the title, etc.). They can be -#' used in any of these functions (which all have a \code{locations} argument): -#' \code{\link{tab_footnote}()}, \code{\link{tab_style}()}, and -#' \code{\link{text_transform}()} Furthermore, multiple locations can be -#' targeted by enclosing several \code{cells_*()} helper functions in a list. +#' used in any of these functions (which all have a `locations` argument): +#' [tab_footnote()], [tab_style()], and [text_transform()] Furthermore, multiple +#' locations can be targeted by enclosing several `cells_*()` helper functions +#' in a list. #' #' The following helper functions can be used to target cells (roughly in order #' from the top to the bottom of a table): #' #' \itemize{ #' -#' \item \code{cells_title()}: targets the table title or the table subtitle -#' depending on the value given to the \code{groups} argument (\code{"title"} or -#' \code{"subtitle"}). +#' \item `cells_title()`: targets the table title or the table subtitle +#' depending on the value given to the `groups` argument (`"title"` or +#' `"subtitle"`). #' -#' \item \code{cells_column_labels()}: targets labels in the column labels (the -#' \code{columns} argument) or the spanner column labels (the \code{groups} +#' \item `cells_column_labels()`: targets labels in the column labels (the +#' `columns` argument) or the spanner column labels (the `groups` #' argument) in the table's column labels part. #' -#' \item \code{cells_group()}: targets the row group labels in any available -#' row groups using the \code{groups} argument. +#' \item `cells_group()`: targets the row group labels in any available +#' row groups using the `groups` argument. #' -#' \item \code{cells_stub()}: targets row labels in the table stub using the -#' \code{rows} argument. +#' \item `cells_stub()`: targets row labels in the table stub using the +#' `rows` argument. #' -#' \item \code{cells_data()}: targets data cells in the table body using -#' intersections of \code{columns} and \code{rows}. +#' \item `cells_data()`: targets data cells in the table body using +#' intersections of `columns` and `rows`. #' -#' \item \code{cells_summary()}: targets summary cells in the table body using -#' the \code{groups} argument and intersections of \code{columns} and -#' \code{rows}. +#' \item `cells_summary()`: targets summary cells in the table body using +#' the `groups` argument and intersections of `columns` and +#' `rows`. #' } #' -#' @param columns,rows,groups either a vector of names, a vector of -#' indices, values provided by \code{\link{vars}()}, values provided by -#' \code{c()}, or a select helper function (see Details for information on -#' these functions). +#' @param columns,rows,groups Either a vector of names, a vector of indices, +#' values provided by [vars()], values provided by `c()`, or a select helper +#' function (see Details for information on these functions). #' #' @examples #' # Use `sp500` to create a gt table; add @@ -221,7 +220,7 @@ #' \if{html}{\figure{man_location_cells_6.svg}{options: width=100\%}} #' #' @name location_cells -#' @return a list object of class \code{location_cells}. +#' @return a list object of class `location_cells`. NULL #' @rdname location_cells @@ -389,10 +388,11 @@ cells_grand_summary <- function(columns = NULL, } #' Interpret input text as Markdown-formatted text -#' @param text the text that is understood to contain Markdown formatting. -#' @return a character object that is tagged for a Markdown-to-HTML +#' +#' @param text The text that is understood to contain Markdown formatting. +#' @return A character object that is tagged for a Markdown-to-HTML #' transformation. -#' @return a character object of class \code{from_markdown}. +#' @return a character object of class `from_markdown`. #' @examples #' # Use `exibble` to create a gt table; #' # when adding a title, use the `md()` @@ -417,11 +417,11 @@ md <- function(text) { } #' Interpret input text as HTML-formatted text -#' @param text,... the text that is understood to be HTML text, which is to be +#' @param text,... The text that is understood to be HTML text, which is to be #' preserved. -#' @return a character object that is tagged as an HTML fragment that is not to +#' @return A character object that is tagged as an HTML fragment that is not to #' be sanitized. -#' @return a character object of class \code{html}. +#' @return a character object of class `html`. #' @examples #' # Use `exibble` to create a gt table; #' # when adding a title, use the `html()` @@ -455,43 +455,40 @@ is.html <- function(x) { #' Helper for defining custom styles for table cells #' -#' This helper function is to be used with the \code{\link{tab_style}()} -#' function, which itself allows for the setting of custom styles to one or more -#' cells. We can also define several styles within a single call of -#' \code{cells_styles} and \code{\link{tab_style}()} will reliably apply those -#' styles to the targeted element. +#' This helper function is to be used with the [tab_style()] function, which +#' itself allows for the setting of custom styles to one or more cells. We can +#' also define several styles within a single call of `cells_styles` and +#' [tab_style()] will reliably apply those styles to the targeted element. #' -#' @param bkgd_color the background color of the cell. -#' @param text_color the text color. -#' @param text_font the font or collection of fonts (subsequent font names are) +#' @param bkgd_color The background color of the cell. +#' @param text_color The text color. +#' @param text_font The font or collection of fonts (subsequent font names are) #' used as fallbacks. -#' @param text_size the size of the font. Can be provided as a number that is -#' assumed to represent \code{px} values (or could be wrapped in the -#' \code{\link{px}()}) helper function. We can also use one of the following -#' absolute size keywords: \code{xx-small}, \code{x-small}, \code{small}, -#' \code{medium}, \code{large}, \code{x-large}, or \code{xx-large}. -#' @param text_style the text style. Can be one of either \code{"center"}, -#' \code{"normal"}, \code{"italic"}, or \code{"oblique"}. -#' @param text_weight the weight of the font. Can be a text-based keyword such -#' as \code{"normal"}, \code{"bold"}, \code{"lighter"}, \code{"bolder"}, or, a -#' numeric value between \code{1} and \code{1000}, inclusive. Note that only -#' variable fonts may support the numeric mapping of weight. -#' @param text_align the text alignment. Can be one of either \code{"center"}, -#' \code{"left"}, \code{"right"}, or \code{"justify"}. -#' @param text_stretch allows for text to either be condensed or expanded. We +#' @param text_size The size of the font. Can be provided as a number that is +#' assumed to represent `px` values (or could be wrapped in the [px()]) helper +#' function. We can also use one of the following absolute size keywords: +#' `xx-small`, `x-small`, `small`, `medium`, `large`, `x-large`, or +#' `xx-large`. +#' @param text_style The text style. Can be one of either `"center"`, +#' `"normal"`, `"italic"`, or `"oblique"`. +#' @param text_weight The weight of the font. Can be a text-based keyword such +#' as `"normal"`, `"bold"`, `"lighter"`, `"bolder"`, or, a numeric value +#' between `1` and `1000`, inclusive. Note that only variable fonts may +#' support the numeric mapping of weight. +#' @param text_align The text alignment. Can be one of either `"center"`, +#' `"left"`, `"right"`, or `"justify"`. +#' @param text_stretch Allows for text to either be condensed or expanded. We #' can use the following text-based keywords to describe the degree of -#' condensation/expansion: \code{ultra-condensed}, \code{extra-condensed}, -#' \code{condensed}, \code{semi-condensed}, \code{normal}, -#' \code{semi-expanded}, \code{expanded}, \code{extra-expanded}, and -#' \code{ultra-expanded}. Alternatively, we can supply percentage values from -#' \code{0\%} to \code{200\%}, inclusive. Negative percentage values are not -#' allowed. -#' @param text_indent the indentation of the text. -#' @param text_decorate allows for text decoration effect to be applied. Here, -#' we can use \code{"overline"}, \code{"line-through"}, or \code{"underline"}. -#' @param text_transform allows for the transformation of text. Options are -#' \code{"uppercase"}, \code{"lowercase"}, or \code{"capitalize"}. -#' @return a character vector containing formatted styles. +#' condensation/expansion: `ultra-condensed`, `extra-condensed`, `condensed`, +#' `semi-condensed`, `normal`, `semi-expanded`, `expanded`, `extra-expanded`, +#' and `ultra-expanded`. Alternatively, we can supply percentage values from +#' `0\%` to `200\%`, inclusive. Negative percentage values are not allowed. +#' @param text_indent The indentation of the text. +#' @param text_decorate Allows for text decoration effect to be applied. Here, +#' we can use `"overline"`, `"line-through"`, or `"underline"`. +#' @param text_transform Allows for the transformation of text. Options are +#' `"uppercase"`, `"lowercase"`, or `"capitalize"`. +#' @return A character vector containing formatted styles. #' @family helper functions #' @export cells_styles <- function(bkgd_color = NULL, @@ -576,8 +573,8 @@ cells_styles <- function(bkgd_color = NULL, #' Helper for providing a numeric value as percentage #' @param x the numeric value to format as a string percentage for some -#' \code{\link{tab_options}()} arguments that can take percentage values -#' (e.g., \code{table.width}). +#' [tab_options()] arguments that can take percentage values +#' (e.g., `table.width`). #' @family helper functions #' @export pct <- function(x) { @@ -590,9 +587,9 @@ pct <- function(x) { } #' Helper for providing a numeric value as pixels value -#' @param x the numeric value to format as a string (e.g., \code{"12px"}) for -#' some \code{\link{tab_options}()} arguments that can take values as units of -#' pixels (e.g., \code{table.font.size}). +#' @param x the numeric value to format as a string (e.g., `"12px"`) for +#' some [tab_options()] arguments that can take values as units of +#' pixels (e.g., `table.font.size`). #' @family helper functions #' @export px <- function(x) { @@ -628,12 +625,12 @@ escape_latex <- function(text) { #' including a \pkg{gt} table can be problematic if we don't have knowledge #' of the LaTeX dependencies. For the most part, these dependencies are the #' LaTeX packages that are required for rendering a \pkg{gt} table. The -#' \code{gt_latex_dependencies()} function provides an object that can be +#' `gt_latex_dependencies()` function provides an object that can be #' used to provide the LaTeX in an Rnw file, allowing \pkg{gt} tables to work #' and not yield errors due to missing packages. #' #' Here is an example Rnw document that shows how the -#' \code{gt_latex_dependencies()} can be used in conjunction with a \pkg{gt} +#' `gt_latex_dependencies()` can be used in conjunction with a \pkg{gt} #' table: #' #' \preformatted{ diff --git a/R/image.R b/R/image.R index 3c8c440a4c..91a8d322cf 100644 --- a/R/image.R +++ b/R/image.R @@ -1,30 +1,28 @@ #' Helper function for adding a local image #' #' We can flexibly add a local image (i.e., an image residing on disk) inside of -#' a table with \code{local_image()} function. The function provides a -#' convenient way to generate an HTML fragment using an on-disk PNG or SVG. -#' Because this function is currently HTML-based, it is only useful for HTML -#' table output. To use this function inside of data cells, it is recommended -#' that the \code{\link{text_transform}()} function is used. With that function, -#' we can specify which data cells to target and then include a -#' \code{local_image()} call within the required user-defined function (for the -#' \code{fn} argument). If we want to include an image in other places (e.g., in -#' the header, within footnote text, etc.) we need to use \code{local_image()} -#' within the \code{\link{html}()} helper function. +#' a table with `local_image()` function. The function provides a convenient way +#' to generate an HTML fragment using an on-disk PNG or SVG. Because this +#' function is currently HTML-based, it is only useful for HTML table output. To +#' use this function inside of data cells, it is recommended that the +#' [text_transform()] function is used. With that function, we can specify which +#' data cells to target and then include a `local_image()` call within the +#' required user-defined function (for the `fn` argument). If we want to include +#' an image in other places (e.g., in the header, within footnote text, etc.) we +#' need to use `local_image()` within the [html()] helper function. #' #' By itself, the function creates an HTML image tag with an image URI embedded #' within. We can easily experiment with a local PNG or SVG image that's -#' available in the \pkg{gt} package using the \code{\link{test_image}()} -#' function. Using that, the call \code{local_image(file = test_image(type = -#' "png"))} evaluates to: +#' available in the \pkg{gt} package using the [test_image()] function. Using +#' that, the call `local_image(file = test_image(type = "png"))` evaluates to: #' -#' \code{ src= style=\"height:30px;\">} +#' ` src= style=\"height:30px;\">` #' -#' where a height of \code{30px} is a default height chosen to work well within -#' the heights of most table rows. +#' where a height of `30px` is a default height chosen to work well within the +#' heights of most table rows. #' -#' @param file a path to an image file. -#' @param height the absolute height (px) of the image in the table cell. +#' @param file A path to an image file. +#' @param height The absolute height (px) of the image in the table cell. #' @return a character object with an HTML fragment that can be placed inside of #' a cell. #' @examples @@ -82,28 +80,28 @@ local_image <- function(file, #' Helper function for adding an image from the web #' -#' We can flexibly add a web image inside of a table with \code{web_image()} +#' We can flexibly add a web image inside of a table with `web_image()` #' function. The function provides a convenient way to generate an HTML fragment #' with an image URL. Because this function is currently HTML-based, it is only #' useful for HTML table output. To use this function inside of data cells, it -#' is recommended that the \code{\link{text_transform}()} function is used. With -#' that function, we can specify which data cells to target and then include a -#' \code{web_image()} call within the required user-defined function (for the -#' \code{fn} argument). If we want to include an image in other places (e.g., in -#' the header, within footnote text, etc.) we need to use \code{web_image()} -#' within the \code{\link{html}()} helper function. +#' is recommended that the [text_transform()] function is used. With that +#' function, we can specify which data cells to target and then include a +#' `web_image()` call within the required user-defined function (for the `fn` +#' argument). If we want to include an image in other places (e.g., in the +#' header, within footnote text, etc.) we need to use `web_image()` within the +#' [html()] helper function. #' #' By itself, the function creates an HTML image tag, so, the call -#' \code{web_image("http://some.web.site/image.png")} evaluates to: +#' `web_image("http://some.web.site/image.png")` evaluates to: #' -#' \code{} +#' `` #' -#' where a height of \code{30px} is a default height chosen to work well within -#' the heights of most table rows. +#' where a height of `30px` is a default height chosen to work well within the +#' heights of most table rows. #' -#' @param url a url that resolves to an image file. -#' @param height the absolute height (px) of the image in the table cell. -#' @return a character object with an HTML fragment that can be placed inside of +#' @param url A url that resolves to an image file. +#' @param height The absolute height (px) of the image in the table cell. +#' @return A character object with an HTML fragment that can be placed inside of #' a cell. #' @examples #' # Get the PNG-based logo for the R @@ -190,38 +188,36 @@ web_image <- function(url, #' Helper function for adding a ggplot #' #' We can add a \pkg{ggplot2} plot inside of a table with the help of the -#' \code{ggplot_image()} function. The function provides a convenient way to -#' generate an HTML fragment with a \code{ggplot} object. Because this function -#' is currently HTML-based, it is only useful for HTML table output. To use this -#' function inside of data cells, it is recommended that the -#' \code{\link{text_transform}()} function is used. With that function, we can -#' specify which data cells to target and then include a call to -#' \code{ggplot_image()} within the required user-defined function (for the -#' \code{fn} argument). If we want to include a plot in other places (e.g., in -#' the header, within footnote text, etc.) we need to use \code{ggplot_image()} -#' within the \code{\link{html}()} helper function. +#' `ggplot_image()` function. The function provides a convenient way to generate +#' an HTML fragment with a `ggplot` object. Because this function is currently +#' HTML-based, it is only useful for HTML table output. To use this function +#' inside of data cells, it is recommended that the [text_transform()] function +#' is used. With that function, we can specify which data cells to target and +#' then include a call to `ggplot_image()` within the required user-defined +#' function (for the `fn` argument). If we want to include a plot in other +#' places (e.g., in the header, within footnote text, etc.) we need to use +#' `ggplot_image()` within the [html()] helper function. #' #' By itself, the function creates an HTML image tag with an image URI embedded -#' within (a 100 dpi PNG). We can easily experiment with any \code{ggplot2} plot -#' object, and using it within \code{ggplot_image(plot_object = } +#' within (a 100 dpi PNG). We can easily experiment with any `ggplot2` plot +#' object, and using it within `ggplot_image(plot_object = ` #' evaluates to: #' -#' \code{ src= style=\"height:100px;\">} +#' ` src= style=\"height:100px;\">` #' -#' where a height of \code{100px} is a default height chosen to work well within -#' the heights of most table rows. There is the option to modify the aspect -#' ratio of the plot (the default \code{aspect_ratio} is \code{1.0}) and this is -#' useful for elongating any given plot to fit better within the table -#' construct. +#' where a height of `100px` is a default height chosen to work well within the +#' heights of most table rows. There is the option to modify the aspect ratio of +#' the plot (the default `aspect_ratio` is `1.0`) and this is useful for +#' elongating any given plot to fit better within the table construct. #' -#' @param plot_object a ggplot plot object. -#' @param height the absolute height (px) of the image in the table cell. -#' @param aspect_ratio the plot's final aspect ratio. Where the height of the -#' plot is fixed using the \code{height} argument, the \code{aspect_ratio} -#' will either compress (\code{aspect_ratio} < \code{1.0}) or expand -#' (\code{aspect_ratio} > \code{1.0}) the plot horizontally. The default value -#' of \code{1.0} will neither compress nor expand the plot. -#' @return a character object with an HTML fragment that can be placed inside of +#' @param plot_object A ggplot plot object. +#' @param height The absolute height (px) of the image in the table cell. +#' @param aspect_ratio The plot's final aspect ratio. Where the height of the +#' plot is fixed using the `height` argument, the `aspect_ratio` +#' will either compress (`aspect_ratio` < `1.0`) or expand +#' (`aspect_ratio` > `1.0`) the plot horizontally. The default value +#' of `1.0` will neither compress nor expand the plot. +#' @return A character object with an HTML fragment that can be placed inside of #' a cell. #' @examples #' library(ggplot2) @@ -296,11 +292,11 @@ ggplot_image <- function(plot_object, #' #' Two test images are available within the \pkg{gt} package. Both contain the #' same imagery (sized at 200px by 200px) but one is a PNG file while the other -#' is an SVG file. This function is most useful when paired with -#' \code{\link{local_image}()} since we test various sizes of the test image -#' within that function. -#' @param type the type of the image, which can either be \code{png} (the -#' default) or \code{svg}. +#' is an SVG file. This function is most useful when paired with [local_image()] +#' since we test various sizes of the test image within that function. +#' +#' @param type The type of the image, which can either be `png` (the default) or +#' `svg`. #' @family image addition functions #' @export test_image <- function(type = c("png", "svg")) { diff --git a/R/info_tables.R b/R/info_tables.R index 853bd2d487..875015e5f9 100644 --- a/R/info_tables.R +++ b/R/info_tables.R @@ -1,10 +1,11 @@ #' View a table with info on date styles #' -#' The \code{fmt_date()} function lets us format date-based values in a -#' convenient manner using preset styles. The table generated by the -#' \code{info_date_style()} function provides a quick reference to all 14 -#' styles, with associated number codes, the format names, and example outputs -#' using a fixed date (\code{2000-02-29}). +#' The `fmt_date()` function lets us format date-based values in a convenient +#' manner using preset styles. The table generated by the `info_date_style()` +#' function provides a quick reference to all 14 styles, with associated number +#' codes, the format names, and example outputs using a fixed date +#' (`2000-02-29`). +#' #' @examples #' # Get a table of info on the different #' # date-formatting styles (which are used @@ -51,11 +52,12 @@ info_date_style <- function() { #' View a table with info on time styles #' -#' The \code{fmt_time()} function lets us format time-based values in a -#' convenient manner using preset styles. The table generated by the -#' \code{info_time_style()} function provides a quick reference to all five -#' styles, with associated number codes, the format names, and example outputs -#' using a fixed time (\code{14:35}). +#' The `fmt_time()` function lets us format time-based values in a convenient +#' manner using preset styles. The table generated by the `info_time_style()` +#' function provides a quick reference to all five styles, with associated +#' number codes, the format names, and example outputs using a fixed time +#' (`14:35`). +#' #' @examples #' # Get a table of info on the different #' # time-formatting styles (which are used @@ -91,28 +93,29 @@ info_time_style <- function() { #' View a table with info on supported currencies #' -#' The \code{fmt_currency()} function lets us format numeric values as -#' currencies. The table generated by the \code{info_currencies()} function -#' provides a quick reference to all the available currencies. The currency -#' identifiers are provided (name, 3-letter currency code, and 3-digit currency -#' code) along with the each currency's exponent value (number of digits of the -#' currency subunits). A formatted example is provided (based on the value of -#' \code{49.95}) to demonstrate the default formatting of each currency. +#' The `fmt_currency()` function lets us format numeric values as currencies. +#' The table generated by the `info_currencies()` function provides a quick +#' reference to all the available currencies. The currency identifiers are +#' provided (name, 3-letter currency code, and 3-digit currency code) along with +#' the each currency's exponent value (number of digits of the currency +#' subunits). A formatted example is provided (based on the value of `49.95`) to +#' demonstrate the default formatting of each currency. #' #' There are 172 currencies, which can lead to a verbose display table. To make #' this presentation more focused on retrieval, we can provide an initial letter -#' corresponding to the 3-letter currency code to \code{begins_with}. This will +#' corresponding to the 3-letter currency code to `begins_with`. This will #' filter currencies in the info table to just the set beginning with the #' supplied letter. #' -#' @param type the type of currency information provided. Can either be -#' \code{code} where currency information corresponding to 3-letter currency -#' codes is provided, or \code{symbol} where currency info for common currency -#' names (e.g., dollar, pound, yen, etc.) is returned. -#' @param begins_with providing a single letter will filter currencies to only +#' @param type The type of currency information provided. Can either be `code` +#' where currency information corresponding to 3-letter currency codes is +#' provided, or `symbol` where currency info for common currency names (e.g., +#' dollar, pound, yen, etc.) is returned. +#' @param begins_with Providing a single letter will filter currencies to only #' those that begin with that letter in their currency code. The default -#' (\code{NULL}) will produce a table with all currencies displayed. This -#' option only constrains the information table where \code{type == "code"}. +#' (`NULL`) will produce a table with all currencies displayed. This option +#' only constrains the information table where `type == "code"`. +#' #' @examples #' # Get a table of info on all of #' # the currencies where the three- @@ -229,23 +232,22 @@ info_currencies <- function(type = c("code", "symbol"), #' View a table with info on supported locales #' -#' Many of the \code{fmt_*()} functions have a \code{locale} argument that makes -#' locale-based formatting easier. The table generated by the -#' \code{info_locales()} function provides a quick reference to all the -#' available locales. The locale identifiers are provided (base locale ID, -#' common display name) along with the each locale's group and decimal separator -#' marks. A formatted numeric example is provided (based on the value of -#' \code{11027}) to demonstrate the default formatting of each locale. +#' Many of the `fmt_*()` functions have a `locale` argument that makes +#' locale-based formatting easier. The table generated by the `info_locales()` +#' function provides a quick reference to all the available locales. The locale +#' identifiers are provided (base locale ID, common display name) along with the +#' each locale's group and decimal separator marks. A formatted numeric example +#' is provided (based on the value of `11027`) to demonstrate the default +#' formatting of each locale. #' #' There are 712 locales, which means that a very long display table is provided #' by default. To trim down the output table size, we can provide an initial -#' letter corresponding to the base locale ID to \code{begins_with}. This will -#' filter locales in the info table to just the set beginning with the supplied -#' letter. +#' letter corresponding to the base locale ID to `begins_with`. This will filter +#' locales in the info table to just the set beginning with the supplied letter. #' -#' @param begins_with providing a single letter will filter locales to only +#' @param begins_with Providing a single letter will filter locales to only #' those that begin with that letter in their base locale ID. The default -#' (\code{NULL}) will produce a table with all locales displayed. +#' (`NULL`) will produce a table with all locales displayed. #' @examples #' # Get a table of info on all of #' # the locales where the base @@ -329,25 +331,25 @@ info_locales <- function(begins_with = NULL) { #' View a table with info on color palettes #' -#' While the \code{\link{data_color}()} function allows us to flexibly color -#' data cells in our \pkg{gt} table, the harder part of this process is -#' discovering and choosing color palettes that are suitable for the table -#' output. We can make this process much easier in two ways: (1) by using the -#' \pkg{paletteer} package, which makes a wide range of palettes from various R -#' packages readily available, and (2) calling the \code{info_paletteer()} -#' function to give us an information table that serves as a quick reference for -#' all of the discrete color palettes available in \pkg{paletteer}. +#' While the [data_color()] function allows us to flexibly color data cells in +#' our \pkg{gt} table, the harder part of this process is discovering and +#' choosing color palettes that are suitable for the table output. We can make +#' this process much easier in two ways: (1) by using the \pkg{paletteer} +#' package, which makes a wide range of palettes from various R packages readily +#' available, and (2) calling the `info_paletteer()` function to give us an +#' information table that serves as a quick reference for all of the discrete +#' color palettes available in \pkg{paletteer}. #' #' The palettes displayed are organized by package and by palette name. These #' values are required when obtaining a palette (as a vector of hexadecimal -#' colors), from the the \code{paletteer::paletteer_d()} function. Once we are +#' colors), from the the `paletteer::paletteer_d()` function. Once we are #' familiar with the names of the color palette packages (e.g., #' \pkg{RColorBrewer}, \pkg{ggthemes}, \pkg{wesanderson}), we can narrow down #' the content of this information table by supplying a vector of such package -#' names to \code{color_pkgs}. +#' names to `color_pkgs`. #' #' Colors from the following color packages (all supported by \pkg{paletteer}) -#' are shown by default with \code{info_paletteer()}: +#' are shown by default with `info_paletteer()`: #' \itemize{ #' \item awtools, 5 palettes #' \item dichromat, 17 palettes @@ -373,9 +375,9 @@ info_locales <- function(begins_with = NULL) { #' \item yarrr, 21 palettes #' } #' -#' @param color_pkgs a vector of color packages that determines which sets of +#' @param color_pkgs A vector of color packages that determines which sets of #' palettes should be displayed in the information table. If this is -#' \code{NULL} (the default) then all of the discrete palettes from all of the +#' `NULL` (the default) then all of the discrete palettes from all of the #' color packages represented in \pkg{paletteer} will be displayed. #' @examples #' # Get a table of info on just the diff --git a/R/modify_columns.R b/R/modify_columns.R index 3e55886fe9..b57c8484d1 100644 --- a/R/modify_columns.R +++ b/R/modify_columns.R @@ -2,28 +2,26 @@ #' #' The individual alignments of columns (which includes the column labels and #' all of their data cells) can be modified. We have the option to align text to -#' the \code{left}, the \code{center}, and the \code{right}. In a less explicit -#' manner, we can allow \pkg{gt} to automatically choose the alignment of each -#' column based on the data type (with the \code{auto} option). -#' -#' When you create a \pkg{gt} table object using \code{\link{gt}()}, automatic -#' alignment of column labels and their data cells is performed. By default, -#' left-alignment is applied to columns of class \code{character}, \code{Date}, -#' or \code{POSIXct}; center-alignment is for columns of class \code{logical}, -#' \code{factor}, or \code{list}; and right-alignment is used for the -#' \code{numeric} and \code{integer} columns. -#' -#' @param data a table object that is created using the \code{\link{gt}()} -#' function. -#' @param align the alignment type. This can be any of \code{"center"}, -#' \code{"left"}, or \code{"right"} for center-, left-, or center-alignment. -#' Alternatively, the \code{"auto"} option (the default), will automatically -#' align values in columns according to the data type (see the Details section -#' for specifics on which alignments are applied). -#' @param columns an optional vector of column names for which the alignment -#' should be applied. If nothing is supplied, or if \code{columns} is -#' \code{TRUE}), then the chosen alignment affects all columns. -#' @return an object of class \code{gt_tbl}. +#' the `left`, the `center`, and the `right`. In a less explicit manner, we can +#' allow \pkg{gt} to automatically choose the alignment of each column based on +#' the data type (with the `auto` option). +#' +#' When you create a \pkg{gt} table object using [gt()], automatic alignment of +#' column labels and their data cells is performed. By default, left-alignment +#' is applied to columns of class `character`, `Date`, or `POSIXct`; +#' center-alignment is for columns of class `logical`, `factor`, or `list`; and +#' right-alignment is used for the `numeric` and `integer` columns. +#' +#' @param data A table object that is created using the [gt()] function. +#' @param align The alignment type. This can be any of `"center"`, `"left"`, or +#' `"right"` for center-, left-, or center-alignment. Alternatively, the +#' `"auto"` option (the default), will automatically align values in columns +#' according to the data type (see the Details section for specifics on which +#' alignments are applied). +#' @param columns An optional vector of column names for which the alignment +#' should be applied. If nothing is supplied, or if `columns` is `TRUE`), then +#' the chosen alignment affects all columns. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # align the `population` column data to @@ -91,31 +89,30 @@ cols_align <- function(data, #' #' Column labels can be modified from their default values (the names of the #' columns from the input table data). When you create a \pkg{gt} table object -#' using \code{\link{gt}()}, column names effectively become the column labels. -#' While this serves as a good first approximation, column names aren't often -#' appealing as column labels in a \pkg{gt} output table. The -#' \code{cols_label()} function provides the flexibility to relabel one or more -#' columns and we even have the option to use the \code{\link{md}()} or -#' \code{\link{html}()} helper functions for rendering column labels from -#' Markdown or using HTML. +#' using [gt()], column names effectively become the column labels. While this +#' serves as a good first approximation, column names aren't often appealing as +#' column labels in a \pkg{gt} output table. The `cols_label()` function +#' provides the flexibility to relabel one or more columns and we even have the +#' option to use the [md()] or [html()] helper functions for rendering column +#' labels from Markdown or using HTML. #' #' It's important to note that while columns can be freely relabeled, we #' continue to refer to columns by their original column names. Column names in -#' a tibble or data frame must be unique whereas column labels in \pkg{gt} -#' have no requirement for uniqueness (which is useful for labeling columns as, -#' say, measurement units that may be repeated several times---usually under +#' a tibble or data frame must be unique whereas column labels in \pkg{gt} have +#' no requirement for uniqueness (which is useful for labeling columns as, say, +#' measurement units that may be repeated several times---usually under #' different spanner column labels). Thus, we can still easily distinguish #' between columns in other \pkg{gt} function calls (e.g., in all of the -#' \code{fmt*()} functions) even though we may lose distinguishability in column +#' `fmt*()` functions) even though we may lose distinguishability in column #' labels once they have been relabeled. #' #' @inheritParams cols_align -#' @param ... one or more named arguments of column names from the input `data` +#' @param ... One or more named arguments of column names from the input `data` #' table along with their labels for display as the column labels. We can -#' optionally wrap the column labels with \code{\link{md}()} (to interpret -#' text as Markdown) or \code{\link{html}()} (to interpret text as HTML). -#' @param .list allows for the use of a list as an input alternative to -#' \code{...}. +#' optionally wrap the column labels with [md()] (to interpret text as +#' Markdown) or [html()] (to interpret text as HTML). +#' @param .list Allows for the use of a list as an input alternative to `...`. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # label all the table's columns to @@ -204,28 +201,27 @@ cols_label <- function(data, #' Move one or more columns #' #' On those occasions where you need to move columns this way or that way, we -#' can make use of the \code{cols_move()} function. While it's true that the -#' movement of columns can be done upstream of \pkg{gt}'s API, it is much easier -#' and less error prone to use the function provided here. The movement -#' procedure here takes one or more specified columns (in the \code{columns} -#' argument) and places them to the right of a different column (the -#' \code{after} argument). The ordering of the \code{columns} to be moved is -#' preserved, as is the ordering of all other columns in the table. -#' -#' The columns supplied in \code{columns} must all exist in the table and none -#' of them can be in the \code{after} argument. The \code{after} column must -#' also exist and only one column should be provided here. If you need to place -#' one or columns at the beginning of the column series, the -#' \code{\link{cols_move_to_start}()} function should be used. Similarly, if -#' those columns to move should be placed at the end of the column series then -#' use \code{\link{cols_move_to_end}()}. +#' can make use of the `cols_move()` function. While it's true that the movement +#' of columns can be done upstream of \pkg{gt}'s API, it is much easier and less +#' error prone to use the function provided here. The movement procedure here +#' takes one or more specified columns (in the `columns` argument) and places +#' them to the right of a different column (the `after` argument). The ordering +#' of the `columns` to be moved is preserved, as is the ordering of all other +#' columns in the table. +#' +#' The columns supplied in `columns` must all exist in the table and none of +#' them can be in the `after` argument. The `after` column must also exist and +#' only one column should be provided here. If you need to place one or columns +#' at the beginning of the column series, the [cols_move_to_start()] function +#' should be used. Similarly, if those columns to move should be placed at the +#' end of the column series then use [cols_move_to_end()]. #' #' @inheritParams cols_align -#' @param columns the column names to move to as a group to a different +#' @param columns The column names to move to as a group to a different #' position. The order of the remaining columns will be preserved. -#' @param after a column name used to anchor the insertion of the moved columns. +#' @param after A column name used to anchor the insertion of the moved columns. #' All of the moved columns will be placed to the right of this column. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # With the remaining columns, position @@ -318,23 +314,23 @@ cols_move <- function(data, #' Move one or more columns to the start #' #' We can easily move set of columns to the beginning of the column series and -#' we only need to specify which \code{columns}. It's possible to do this -#' upstream of \pkg{gt}'s API, however, it is easier with this function and it -#' presents less possibility for error. The ordering of the \code{columns} that -#' are moved to the start is preserved (same with the ordering of all other -#' columns in the table). -#' -#' The columns supplied in \code{columns} must all exist in the table. If you -#' need to place one or columns at the end of the column series, the -#' \code{\link{cols_move_to_end}()} function should be used. More control is -#' offered with the \code{\link{cols_move}()} function, where columns could be -#' placed after a specific column. +#' we only need to specify which `columns`. It's possible to do this upstream of +#' \pkg{gt}'s API, however, it is easier with this function and it presents less +#' possibility for error. The ordering of the `columns` that are moved to the +#' start is preserved (same with the ordering of all other columns in the +#' table). +#' +#' The columns supplied in `columns` must all exist in the table. If you need to +#' place one or columns at the end of the column series, the +#' [cols_move_to_end()] function should be used. More control is offered with +#' the [cols_move()] function, where columns could be placed after a specific +#' column. #' #' @inheritParams cols_align -#' @param columns the column names to move to the left-most side of the table. +#' @param columns The column names to move to the left-most side of the table. #' The order in which columns are provided will be preserved (as is the case #' with the remaining columns). -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # With the remaining columns, move the @@ -406,23 +402,22 @@ cols_move_to_start <- function(data, #' Move one or more columns to the end #' #' It's possible to move a set of columns to the end of the column series, we -#' only need to specify which \code{columns} are to be moved. While this can be -#' done upstream of \pkg{gt}'s API, this function makes to process much easier -#' and it's less error prone. The ordering of the \code{columns} that are moved -#' to the end is preserved (same with the ordering of all other columns in the -#' table). +#' only need to specify which `columns` are to be moved. While this can be done +#' upstream of \pkg{gt}'s API, this function makes to process much easier and +#' it's less error prone. The ordering of the `columns` that are moved to the +#' end is preserved (same with the ordering of all other columns in the table). #' -#' The columns supplied in \code{columns} must all exist in the table. If you -#' need to place one or columns at the start of the column series, the -#' \code{\link{cols_move_to_start}()} function should be used. More control is -#' offered with the \code{\link{cols_move}()} function, where columns could be -#' placed after a specific column. +#' The columns supplied in `columns` must all exist in the table. If you need to +#' place one or columns at the start of the column series, the +#' [cols_move_to_start()] function should be used. More control is offered with +#' the [cols_move()] function, where columns could be placed after a specific +#' column. #' #' @inheritParams cols_align -#' @param columns the column names to move to the right-most side of the table. +#' @param columns The column names to move to the right-most side of the table. #' The order in which columns are provided will be preserved (as is the case #' with the remaining columns). -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # With the remaining columns, move the @@ -496,26 +491,26 @@ cols_move_to_end <- function(data, #' Hide one or more columns #' -#' The \code{cols_hide()} function allows us to hide one or more columns from +#' The `cols_hide()` function allows us to hide one or more columns from #' appearing in the final output table. While it's possible and often desirable -#' to omit columns from the input table data before introduction to the -#' \code{\link{gt}()} function, there can be cases where the data in certain -#' columns is useful (as a column reference during formatting of other columns) -#' but the final display of those columns is not necessary. +#' to omit columns from the input table data before introduction to the [gt()] +#' function, there can be cases where the data in certain columns is useful (as +#' a column reference during formatting of other columns) but the final display +#' of those columns is not necessary. #' #' The hiding of columns is internally a rendering directive, so, all columns #' that are 'hidden' are still accessible and useful in any expression provided -#' to a \code{rows} argument. Furthermore, the \code{cols_hide()} function (as -#' with many \pkg{gt} functions) can be placed anywhere in a pipeline of -#' \pkg{gt} function calls (acting as a promise to hide columns when the timing -#' is right). However there's perhaps greater readability when placing this call -#' closer to the end of such a pipeline. +#' to a `rows` argument. Furthermore, the `cols_hide()` function (as with many +#' \pkg{gt} functions) can be placed anywhere in a pipeline of \pkg{gt} function +#' calls (acting as a promise to hide columns when the timing is right). However +#' there's perhaps greater readability when placing this call closer to the end +#' of such a pipeline. #' #' @inheritParams cols_align -#' @param columns the column names to hide from the output display table. The +#' @param columns The column names to hide from the output display table. The #' order of the remaining columns will be preserved. Values provided that do #' not correspond to column names will be disregarded. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `countrypops` to create a gt table; #' # Hide the columns `country_code_2` and @@ -591,26 +586,25 @@ cols_hide <- function(data, #' reference to individual columns must continue to be the column names from the #' input table data (which are unique by necessity). #' -#' If we look to the column names in the \code{iris} dataset as an example of -#' how \code{cols_split_delim()} might be useful, we find the names -#' \code{Sepal.Length}, \code{Sepal.Width}, \code{Petal.Length}, -#' \code{Petal.Width}. From this naming system, it's easy to see that the -#' \code{Sepal} and \code{Petal} can group together the repeated common -#' \code{Length} and \code{Width} values. In your own datasets, we can avoid a -#' lengthy relabeling with \code{\link{cols_label}()} if column names can be -#' fashioned beforehand to contain both the spanner column label and the column -#' label. An additional advantage is that the column names in the input table -#' data remain unique even though there may eventually be repeated column labels -#' in the rendered output table). +#' If we look to the column names in the `iris` dataset as an example of how +#' `cols_split_delim()` might be useful, we find the names `Sepal.Length`, +#' `Sepal.Width`, `Petal.Length`, `Petal.Width`. From this naming system, it's +#' easy to see that the `Sepal` and `Petal` can group together the repeated +#' common `Length` and `Width` values. In your own datasets, we can avoid a +#' lengthy relabeling with [cols_label()] if column names can be fashioned +#' beforehand to contain both the spanner column label and the column label. An +#' additional advantage is that the column names in the input table data remain +#' unique even though there may eventually be repeated column labels in the +#' rendered output table). #' #' @inheritParams cols_align -#' @param delim the delimiter to use to split an input column name. The +#' @param delim The delimiter to use to split an input column name. The #' delimiter supplied will be autoescaped for the internal splitting #' procedure. The first component of the split will become the group name and #' the second component will be the column label. -#' @param columns an optional vector of column names that this operation should +#' @param columns An optional vector of column names that this operation should #' be limited to. The default is to consider all columns in the table. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `iris` to create a gt table; split #' # any columns that are dot-separated @@ -673,31 +667,30 @@ cols_split_delim <- function(data, #' #' This function takes any two columns and merges them into a single column, #' using a pattern that specifies how the values in the data cells are combined. -#' We specify the columns to merge together in the \code{col_1} and \code{col_2} -#' arguments and the string-combining pattern is specified in \code{pattern}. -#' The column that is retained is that of \code{col_1} whereas the column -#' specified in \code{col_2} is dropped from the output table. +#' We specify the columns to merge together in the `col_1` and `col_2` arguments +#' and the string-combining pattern is specified in `pattern`. The column that +#' is retained is that of `col_1` whereas the column specified in `col_2` is +#' dropped from the output table. #' #' There are two other column-merging functions that offer specialized behavior -#' that is optimized for common table tasks: \code{\link{cols_merge_range}()} -#' and \code{\link{cols_merge_uncert}()}. These functions operate similarly, -#' where the second column specified is dropped from the output table. For all -#' of the \code{cols_merge*()} functions, column removal occurs late in the -#' rendering lifecycle so those secondary columns are still usable as column -#' references (e.g., inside expressions provided to `rows` in the \code{fmt*()} -#' functions). +#' that is optimized for common table tasks: [cols_merge_range()] and +#' [cols_merge_uncert()]. These functions operate similarly, where the second +#' column specified is dropped from the output table. For all of the +#' `cols_merge*()` functions, column removal occurs late in the rendering +#' lifecycle so those secondary columns are still usable as column references +#' (e.g., inside expressions provided to `rows` in the `fmt*()` functions). #' #' @inheritParams cols_align -#' @param col_1 a retained column that contains values to be merged with those -#' in \code{col_2}. -#' @param col_2 a column that contains values to be merged with those in -#' \code{col_1}. This column will be discarded but is still useful as a -#' reference in other \pkg{gt} functions. -#' @param pattern a formatting pattern that specifies the arrangement of the -#' \code{col_1} and \code{col_1} values and any string literals. The -#' \code{col_1} column is represented as \code{{1}} whereas \code{col_2} is -#' \code{{2}}. All other characters are taken to be string literals. -#' @return an object of class \code{gt_tbl}. +#' @param col_1 A retained column that contains values to be merged with those +#' in `col_2`. +#' @param col_2 A column that contains values to be merged with those in +#' `col_1`. This column will be discarded but is still useful as a reference +#' in other \pkg{gt} functions. +#' @param pattern A formatting pattern that specifies the arrangement of the +#' `col_1` and `col_1` values and any string literals. The `col_1` column is +#' represented as `{1}` whereas `col_2` is `{2}`. All other characters are +#' taken to be string literals. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `sp500` to create a gt table; #' # merge the `open` & `close` columns @@ -779,48 +772,46 @@ cols_merge <- function(data, #' Merge two columns to a value & uncertainty column #' -#' The \code{cols_merge_uncert()} function is a specialized variant of the -#' \code{\link{cols_merge}()} function. It operates by taking a base value -#' column (\code{col_val}) and an uncertainty column (\code{col_uncert}) and -#' merges them into a single column. What results is a column with values and -#' associated uncertainties (e.g., \code{12.0 ± 0.1}), and, the column specified -#' in \code{col_uncert} is dropped from the output table. +#' The `cols_merge_uncert()` function is a specialized variant of the +#' [cols_merge()] function. It operates by taking a base value column +#' (`col_val`) and an uncertainty column (`col_uncert`) and merges them into a +#' single column. What results is a column with values and associated +#' uncertainties (e.g., `12.0 ± 0.1`), and, the column specified in `col_uncert` +#' is dropped from the output table. #' -#' This function could be somewhat replicated using \code{\link{cols_merge}()}, -#' however, \code{cols_merge_uncert()} employs the following specialized -#' semantics for \code{NA} handling: +#' This function could be somewhat replicated using [cols_merge()], however, +#' `cols_merge_uncert()` employs the following specialized semantics for `NA` +#' handling: #' #' \enumerate{ #' -#' \item \code{NA}s in \code{col_val} result in missing values for the merged -#' column (e.g., \code{NA} + \code{0.1} = \code{NA}) +#' \item `NA`s in `col_val` result in missing values for the merged +#' column (e.g., `NA` + `0.1` = `NA`) #' -#' \item \code{NA}s in \code{col_uncert} (but not \code{col_val}) result in +#' \item `NA`s in `col_uncert` (but not `col_val`) result in #' base values only for the merged column (e.g., -#' \code{12.0} + \code{NA} = \code{12.0}) +#' `12.0` + `NA` = `12.0`) #' -#' \item \code{NA}s both \code{col_val} and \code{col_uncert} result in -#' missing values for the merged column (e.g., \code{NA} + \code{NA} = -#' \code{NA}) +#' \item `NA`s both `col_val` and `col_uncert` result in +#' missing values for the merged column (e.g., `NA` + `NA` = +#' `NA`) #' } #' -#' Any resulting \code{NA} values in the \code{col_val} column following the -#' merge operation can be easily formatted using the \code{\link{fmt_missing}()} -#' function. +#' Any resulting `NA` values in the `col_val` column following the merge +#' operation can be easily formatted using the [fmt_missing()] function. #' #' This function is part of a set of three column-merging functions. The other -#' two are the general \code{\link{cols_merge}()} function and the specialized -#' \code{\link{cols_merge_range}()} function. These functions operate similarly, -#' where the second column specified is dropped from the output table. For all -#' of the \code{cols_merge*()} functions, column removal occurs late in the -#' rendering lifecycle so those secondary columns are still usable as column -#' references (e.g., inside expressions provided to `rows` in the \code{fmt*()} -#' functions). +#' two are the general [cols_merge()] function and the specialized +#' [cols_merge_range()] function. These functions operate similarly, where the +#' second column specified is dropped from the output table. For all of the +#' `cols_merge*()` functions, column removal occurs late in the rendering +#' lifecycle so those secondary columns are still usable as column references +#' (e.g., inside expressions provided to `rows` in the `fmt*()` functions). #' #' @inheritParams cols_align -#' @param col_val a single column name that contains the base values. -#' @param col_uncert a single column name that contains the uncertainty values. -#' @return an object of class \code{gt_tbl}. +#' @param col_val A single column name that contains the base values. +#' @param col_uncert A single column name that contains the uncertainty values. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table, #' # keeping only the `currency` and `num` @@ -901,48 +892,46 @@ cols_merge_uncert <- function(data, #' Merge two columns to a value range column #' -#' The \code{cols_merge_range()} function is a specialized variant of the -#' \code{\link{cols_merge}()} function. It operates by taking a two columns that -#' constitute a range of values (\code{col_begin} and \code{col_end}) and merges -#' them into a single column. What results is a column containing both values -#' separated by a long dash (e.g., \code{12.0 — 20.0}). The column specified in -#' \code{col_end} is dropped from the output table. +#' The `cols_merge_range()` function is a specialized variant of the +#' [cols_merge()] function. It operates by taking a two columns that constitute +#' a range of values (`col_begin` and `col_end`) and merges them into a single +#' column. What results is a column containing both values separated by a long +#' dash (e.g., `12.0 — 20.0`). The column specified in `col_end` is dropped from +#' the output table. #' -#' This function could be somewhat replicated using \code{\link{cols_merge}()}, -#' however, \code{cols_merge_range()} employs the following specialized -#' semantics for \code{NA} handling: +#' This function could be somewhat replicated using [cols_merge()], however, +#' `cols_merge_range()` employs the following specialized semantics for `NA` +#' handling: #' #' \enumerate{ #' -#' \item \code{NA}s in \code{col_begin} result in missing values for the merged -#' column (e.g., \code{NA} + \code{20.0} = \code{NA}) +#' \item `NA`s in `col_begin` result in missing values for the merged +#' column (e.g., `NA` + `20.0` = `NA`) #' -#' \item \code{NA}s in \code{col_end} (but not \code{col_begin}) result in -#' a display of only the \code{col_begin} values only for the merged column -#' (e.g., \code{12.0} + \code{NA} = \code{12.0}) +#' \item `NA`s in `col_end` (but not `col_begin`) result in +#' a display of only the `col_begin` values only for the merged column +#' (e.g., `12.0` + `NA` = `12.0`) #' -#' \item \code{NA}s both \code{col_begin} and \code{col_end} result in -#' missing values for the merged column (e.g., \code{NA} + \code{NA} = -#' \code{NA}) +#' \item `NA`s both `col_begin` and `col_end` result in +#' missing values for the merged column (e.g., `NA` + `NA` = +#' `NA`) #' } #' -#' Any resulting \code{NA} values in the \code{col_begin} column following the -#' merge operation can be easily formatted using the \code{\link{fmt_missing}()} -#' function. +#' Any resulting `NA` values in the `col_begin` column following the merge +#' operation can be easily formatted using the [fmt_missing()] function. #' #' This function is part of a set of three column-merging functions. The other -#' two are the general \code{\link{cols_merge}()} function and the specialized -#' \code{\link{cols_merge_uncert}()} function. These functions operate -#' similarly, where the second column specified is dropped from the output -#' table. For all of the \code{cols_merge*()} functions, column removal occurs -#' late in the rendering lifecycle so those secondary columns are still usable -#' as column references (e.g., inside expressions provided to `rows` in the -#' \code{fmt*()} functions). +#' two are the general [cols_merge()] function and the specialized +#' [cols_merge_uncert()] function. These functions operate similarly, where the +#' second column specified is dropped from the output table. For all of the +#' `cols_merge*()` functions, column removal occurs late in the rendering +#' lifecycle so those secondary columns are still usable as column references +#' (e.g., inside expressions provided to `rows` in the `fmt*()` functions). #' #' @inheritParams cols_align -#' @param col_begin a column that contains values for the start of the range. -#' @param col_end a column that contains values for the end of the range. -#' @return an object of class \code{gt_tbl}. +#' @param col_begin A column that contains values for the start of the range. +#' @param col_end A column that contains values for the end of the range. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table, #' # keeping only the `model`, `mpg_c`, diff --git a/R/modify_rows.R b/R/modify_rows.R index 6e844fa036..8153d32652 100644 --- a/R/modify_rows.R +++ b/R/modify_rows.R @@ -1,20 +1,20 @@ #' Modify the ordering of any row groups #' #' We can modify the display order of any row groups in a \pkg{gt} object with -#' the \code{row_group_order()} function. The \code{groups} argument can either -#' take a vector of row group names or a numeric vector of row group indices; -#' whichever is provided, the row groups will adhere to this revised ordering. -#' It isn't necessary to provide all row group names in \code{groups}, rather, -#' what is provided will assume the specified ordering at the top of the table -#' and the remaining row groups will follow in their original ordering. +#' the `row_group_order()` function. The `groups` argument can either take a +#' vector of row group names or a numeric vector of row group indices; whichever +#' is provided, the row groups will adhere to this revised ordering. It isn't +#' necessary to provide all row group names in `groups`, rather, what is +#' provided will assume the specified ordering at the top of the table and the +#' remaining row groups will follow in their original ordering. #' @inheritParams cols_align -#' @param groups a vector of row group names, or, a numeric vector of indices +#' @param groups A vector of row group names, or, a numeric vector of indices #' corresponding to the new ordering. Either vector must correspond to #' assigned group names or the index positions. Also, either type of vector is #' not required to have all of the row group names or available index #' positions within it; any omitted values will be added to the end while #' preserving the original ordering. -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table #' # with a stub and with row groups; diff --git a/R/print.R b/R/print.R index 8441ae666b..0339e5cda1 100644 --- a/R/print.R +++ b/R/print.R @@ -1,7 +1,7 @@ #' Print the table #' #' This facilitates printing of the HTML table to the R console. -#' @param x an object of class \code{gt_tbl}. +#' @param x An object of class `gt_tbl`. #' @keywords internal #' @export print.gt_tbl <- function(x, ..., view = interactive()) { @@ -20,7 +20,7 @@ knitr_is_rtf_output <- function() { #' Knit print the table #' #' This facilitates printing of the HTML table within a knitr code chunk. -#' @param x an object of class \code{gt_tbl}. +#' @param x An object of class `gt_tbl`. #' @keywords internal knit_print.gt_tbl <- function(x, ...) { diff --git a/R/render_as_html.R b/R/render_as_html.R index 60c2f2233a..7afe41a9ec 100644 --- a/R/render_as_html.R +++ b/R/render_as_html.R @@ -1,8 +1,8 @@ #' Transform a \pkg{gt} table object to an HTML table #' -#' Take a \code{gt_tbl} table object and transform it to an HTML table. -#' @param data a table object that is created using the \code{gt()} function. -#' @return a character object with an HTML table +#' Take a `gt_tbl` table object and transform it to an HTML table. +#' @param data A table object that is created using the `gt()` function. +#' @return A character object with an HTML table #' @import checkmate #' @import rlang #' @family table export functions diff --git a/R/resolver.R b/R/resolver.R index 981eac16bb..941bad0a37 100644 --- a/R/resolver.R +++ b/R/resolver.R @@ -1,6 +1,7 @@ #' Resolve the `cells_data` object once it has access to the `data` object -#' @param data a table object that is created using the \code{gt()} function. -#' @param object the list object created by the \code{cells_data()} function. +#' +#' @param data A table object that is created using the `gt()` function. +#' @param object The list object created by the `cells_data()` function. #' @importFrom dplyr arrange distinct #' @noRd resolve_cells_data <- function(data, @@ -46,8 +47,9 @@ resolve_cells_data <- function(data, } #' Resolve the `cells_stub` object once it has access to the `data` object -#' @param data a table object that is created using the \code{gt()} function. -#' @param object the list object created by the \code{cells_stub()} function. +#' +#' @param data A table object that is created using the `gt()` function. +#' @param object The list object created by the `cells_stub()` function. #' @noRd resolve_cells_stub <- function(data, object) { @@ -81,8 +83,9 @@ resolve_cells_stub <- function(data, #' Resolve the `cells_column_labels` object once it has access to the `data` #' object -#' @param data a table object that is created using the \code{gt()} function. -#' @param object the list object created by the \code{cells_column_labels()} +#' +#' @param data A table object that is created using the `gt()` function. +#' @param object The list object created by the `cells_column_labels()` #' function. #' @noRd resolve_cells_column_labels <- function(data, @@ -110,9 +113,9 @@ resolve_cells_column_labels <- function(data, #' Resolve expressions to obtain column indices #' #' @param var_expr An expression to evaluate. This is passed directly to -#' \code{rlang::eval_tidy()} as a value for the \code{expr} argument. -#' @param data The input table available in \code{data} (usually accessed -#' through \code{as.data.frame(data)}). +#' `rlang::eval_tidy()` as a value for the `expr` argument. +#' @param data The input table available in `data` (usually accessed through +#' `as.data.frame(data)`). #' @noRd resolve_vars_idx <- function(var_expr, data) { @@ -129,10 +132,10 @@ resolve_vars_idx <- function(var_expr, #' Resolve expressions to obtain row indices #' #' @param var_expr An expression to evaluate. This is passed directly to -#' \code{rlang::eval_tidy()} as a value for the \code{expr} argument. -#' @param data The input table available in \code{data} (usually accessed -#' through \code{as.data.frame(data)}). -#' @param vals The names of columns or rows in \code{data}. +#' `rlang::eval_tidy()` as a value for the `expr` argument. +#' @param data The input table available in `data` (usually accessed through +#' `as.data.frame(data)`). +#' @param vals The names of columns or rows in `data`. #' @import tidyselect #' @import rlang #' @importFrom dplyr between @@ -213,8 +216,7 @@ resolve_data_vals_idx <- function(var_expr, #' Resolve expressions to obtain column names #' #' @param var_expr The immutable column names from the input table. -#' @param data A table object that is created using the \code{\link{gt}()} -#' function. +#' @param data A table object that is created using the [gt()] function. #' @noRd resolve_vars <- function(var_expr, data) { diff --git a/R/shiny.R b/R/shiny.R index 377a1a70b6..87f0c6b265 100644 --- a/R/shiny.R +++ b/R/shiny.R @@ -1,11 +1,12 @@ #' A \pkg{gt} display table render function for use in Shiny -#' @param expr an expression that creates a \pkg{gt} table object. -#' @param env the environment in which to evaluate the \code{expr}. -#' @param quoted is expr a quoted expression (with \code{quote()})? This is -#' useful if you want to save an expression in a variable. +#' +#' @param expr An expression that creates a \pkg{gt} table object. +#' @param env The environment in which to evaluate the `expr`. +#' @param quoted Is `expr`` a quoted expression (with `quote()`)? This is useful +#' if you want to save an expression in a variable. #' @param outputArgs A list of arguments to be passed through to the implicit -#' call to \code{\link{gt_output}()} when \code{render_gt} is used in an -#' interactive R Markdown document. +#' call to [gt_output()] when `render_gt` is used in an interactive R Markdown +#' document. #' @seealso \link{gt_output}() #' @family Shiny functions #' @importFrom htmltools resolveDependencies findDependencies doRenderTags @@ -45,7 +46,8 @@ render_gt <- function(expr, } #' Create a \pkg{gt} display table output element for Shiny -#' @param outputId an output variable from which to read the table. +#' +#' @param outputId An output variable from which to read the table. #' @return A \pkg{gt} table output element that can be included in a panel. #' @seealso \link{render_gt}() #' @family Shiny functions diff --git a/R/summary_rows.R b/R/summary_rows.R index db345bc761..0d8742af9b 100644 --- a/R/summary_rows.R +++ b/R/summary_rows.R @@ -1,49 +1,46 @@ #' Add summary rows using aggregation functions #' #' Add groupwise summary rows to one or more row groups by using the input data -#' already provided in the \code{\link{gt}()} function alongside any suitable -#' aggregation functions. Or, add a grand summary that incorporates all -#' available data, regardless of grouping. You choose how to format the values -#' in the resulting summary cells by use of a \code{formatter} function (e.g, -#' \code{\link{fmt_number}()}) and any relevant options. +#' already provided in the [gt()] function alongside any suitable aggregation +#' functions. Or, add a grand summary that incorporates all available data, +#' regardless of grouping. You choose how to format the values in the resulting +#' summary cells by use of a `formatter` function (e.g, `fmt_number`) and any +#' relevant options. #' #' Should we need to obtain the summary data for external purposes, the -#' \code{\link{extract_summary}()} function can be used with a \code{gt_tbl} -#' object where summary rows were added via \code{summary_rows()}. +#' [extract_summary()] function can be used with a `gt_tbl` object where summary +#' rows were added via `summary_rows()`. #' -#' @param data A table object that is created using the \code{gt()} function. +#' @param data A table object that is created using the [gt()] function. #' @param groups The groups to consider for generation of groupwise summary -#' rows. By default this is set to \code{NULL}, which results in the formation -#' of grand summary rows (a grand summary operates on all table data). -#' Providing the names of row groups in \code{c()} will create a groupwise -#' summary and generate summary rows for the specified groups. Setting this to -#' \code{TRUE} indicates that all available groups will receive groupwise -#' summary rows. +#' rows. By default this is set to `NULL`, which results in the formation of +#' grand summary rows (a grand summary operates on all table data). Providing +#' the names of row groups in [c()] will create a groupwise summary and +#' generate summary rows for the specified groups. Setting this to `TRUE` +#' indicates that all available groups will receive groupwise summary rows. #' @param columns The columns for which the summaries should be calculated. #' @param fns Functions used for aggregations. This can include base functions -#' like \code{mean}, \code{min}, \code{max}, \code{median}, \code{sd}, or -#' \code{sum} or any other user-defined aggregation function. The function(s) -#' should be supplied within a \code{list()}. Within that list, we can specify -#' the functions by use of function names in quotes (e.g., \code{"sum"}), as -#' bare functions (e.g., \code{sum}), or as one-sided R formulas using a -#' leading \code{~}. In the formula representation, a \code{.} serves as the -#' data to be summarized (e.g., \code{sum(., na.rm = TRUE)}). The use of named -#' arguments is recommended as the names will serve as summary row labels for -#' the corresponding summary rows data (the labels can derived from the -#' function names but only when not providing bare function names). -#' @param missing_text The text to be used in place of \code{NA} values in -#' summary cells with no data outputs. -#' @param formatter A formatter function name. These can be any of the -#' \code{fmt_*()}functions available in the package (e.g., -#' \code{\link{fmt_number}()}, \code{link{fmt_percent}()}, etc.), or a custom -#' function using \code{\link{fmt}()}. The default function is -#' \code{\link{fmt_number}()} and its options can be accessed through -#' \code{...}. -#' @param ... Values passed to the \code{formatter} function, where the provided +#' like `mean`, `min`, `max`, `median`, `sd`, or `sum` or any other +#' user-defined aggregation function. The function(s) should be supplied +#' within a `list()`. Within that list, we can specify the functions by use of +#' function names in quotes (e.g., `"sum"`), as bare functions (e.g., `sum`), +#' or as one-sided R formulas using a leading `~`. In the formula +#' representation, a `.` serves as the data to be summarized (e.g., `sum(., +#' na.rm = TRUE)`). The use of named arguments is recommended as the names +#' will serve as summary row labels for the corresponding summary rows data +#' (the labels can derived from the function names but only when not providing +#' bare function names). +#' @param missing_text The text to be used in place of `NA` values in summary +#' cells with no data outputs. +#' @param formatter A formatter function name. These can be any of the `fmt_*()` +#' functions available in the package (e.g., [fmt_number()], [fmt_percent()], +#' etc.), or a custom function using `fmt()`. The default function is +#' [fmt_number()] and its options can be accessed through `...`. +#' @param ... Values passed to the `formatter` function, where the provided #' values are to be in the form of named vectors. For example, when using the -#' default \code{formatter} function, \code{\link{fmt_number}()}, options such -#' as \code{decimals}, \code{use_seps}, and \code{locale} can be used. -#' @return An object of class \code{gt_tbl}. +#' default `formatter` function, [fmt_number()], options such as `decimals`, +#' `use_seps`, and `locale` can be used. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `sp500` to create a gt table with #' # row groups; create summary rows (`min`, diff --git a/R/tab_footnote.R b/R/tab_footnote.R index eaee3b47dd..ac25cabd18 100644 --- a/R/tab_footnote.R +++ b/R/tab_footnote.R @@ -1,46 +1,39 @@ #' Add a table footnote #' -#' The \code{tab_footnote()} function can make it a painless process to add a +#' The `tab_footnote()` function can make it a painless process to add a #' footnote to a \pkg{gt} table. There are two components to a footnote: (1) a #' glyph that is attached to the targeted cell text, and (2) the footnote text #' (that starts with the corresponding glyph) that is placed in the table's -#' footer area. Each call of \code{tab_footnote()} will add a different note, -#' and one or more cells can be targeted via the location helper functions -#' (e.g., \code{\link{cells_data}()}, \code{\link{cells_column_labels}()}, -#' etc.). +#' footer area. Each call of `tab_footnote()` will add a different note, and one +#' or more cells can be targeted via the location helper functions (e.g., +#' [cells_data()], [cells_column_labels()], etc.). #' #' The formatting of the footnotes can be controlled through the use of various -#' parameters in the \code{\link{tab_options}()} function: +#' parameters in the [tab_options()] function: #' -#' \itemize{ -#' \item \code{footnote.sep}: allows for a choice of the separator between +#' \itemize{ \item `footnote.sep`: allows for a choice of the separator between #' consecutive footnotes in the table footer. By default, this is set to a -#' linebreak. -#' \item \code{footnote.glyph}: the set of sequential characters or numbers -#' used to identify the footnotes. -#' \item \code{footnote.font.size}: the size of the font used in the footnote -#' section. -#' \item \code{footnote.padding}: the amount of padding to apply between the -#' footnote and source note sections in the table footer. -#' } +#' linebreak. \item `footnote.glyph`: the set of sequential characters or +#' numbers used to identify the footnotes. \item `footnote.font.size`: the size +#' of the font used in the footnote section. \item `footnote.padding`: the +#' amount of padding to apply between the footnote and source note sections in +#' the table footer. } #' #' @inheritParams fmt_number -#' @param footnote the text to be used in the footnote. We can optionally use -#' the \code{\link{md}()} and \code{\link{html}()} functions to style the text -#' as Markdown or to retain HTML elements in the footnote text. -#' @param locations the cell or set of cells to be associated with the footnote. -#' Supplying any of the \code{cells_*()} helper functions is a useful way to -#' target the location cells that are associated with the footnote text. These -#' helper functions are: \code{\link{cells_title}()}, -#' \code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -#' \code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -#' \code{\link{cells_summary}()}. Please see the help article -#' \link{location_cells} for more information on how these helper functions -#' can be used. Additionally, we can enclose several \code{cells_*()} calls -#' within a \code{list()} if we wish to link the footnote text to different +#' @param footnote The text to be used in the footnote. We can optionally use +#' the [md()] and [html()] functions to style the text as Markdown or to +#' retain HTML elements in the footnote text. +#' @param locations The cell or set of cells to be associated with the footnote. +#' Supplying any of the `cells_*()` helper functions is a useful way to target +#' the location cells that are associated with the footnote text. These helper +#' functions are: [cells_title()], [cells_column_labels()], [cells_group()], +#' [cells_stub()], [cells_data()], and [cells_summary()]. Please see the help +#' article \link{location_cells} for more information on how these helper +#' functions can be used. Additionally, we can enclose several `cells_*()` +#' calls within a `list()` if we wish to link the footnote text to different #' types of locations (e.g., cell data values, stub group headings, the table #' title, etc.). -#' @return an object of class \code{gt_tbl}. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `sza` to create a gt table; color #' # the `sza` column using the `data_color()` diff --git a/R/tab_options.R b/R/tab_options.R index 39e15ac117..6cbcf7b1c8 100644 --- a/R/tab_options.R +++ b/R/tab_options.R @@ -3,63 +3,61 @@ #' Modify the options available in a table. These options are named by the #' components, the subcomponents, and the element that can adjusted. #' @inheritParams fmt_number -#' @param table.width the width of the table. Can be specified as a +#' @param table.width The width of the table. Can be specified as a #' single-length character with units of pixels or as a percentage. If #' provided as a single-length numeric vector, it is assumed that the value is -#' given in units of pixels. The \code{\link{px}()} and \code{\link{pct}()} -#' helper functions can also be used to pass in numeric values and obtain -#' values as pixel or percent units. +#' given in units of pixels. The [px()] and [pct()] helper functions can also +#' be used to pass in numeric values and obtain values as pixel or percent +#' units. #' @param table.font.size,heading.title.font.size,heading.subtitle.font.size,column_labels.font.size,row_group.font.size,footnote.font.size,sourcenote.font.size -#' font sizes for the parent text element \code{table} and the following child -#' elements: \code{heading.title}, \code{heading.subtitle}, \code{columns}, -#' \code{row_group}, \code{footnote}, and \code{sourcenote}. Can be specified -#' as a single-length character vector with units of pixels (e.g., -#' \code{12px}) or as a percentage (e.g., \code{80\%}). If provided as a -#' single-length numeric vector, it is assumed that the value is given in -#' units of pixels. The \code{\link{px}()} and \code{\link{pct}()} helper +#' Font sizes for the parent text element `table` and the following child +#' elements: `heading.title`, `heading.subtitle`, `columns`, `row_group`, +#' `footnote`, and `sourcenote`. Can be specified as a single-length character +#' vector with units of pixels (e.g., `12px`) or as a percentage (e.g., +#' `80\%`). If provided as a single-length numeric vector, it is assumed that +#' the value is given in units of pixels. The [px()] and [pct()] helper #' functions can also be used to pass in numeric values and obtain values as #' pixel or percent units. #' @param column_labels.font.weight,row_group.font.weight the font weight of -#' the \code{columns} and \code{row_group} text element. +#' the `columns` and `row_group` text element. #' @param summary_row.text_transform,grand_summary_row.text_transform an option #' to apply text transformations to the label text in each summary row. #' @param table.background.color,heading.background.color,column_labels.background.color,row_group.background.color,summary_row.background.color,grand_summary_row.background.color -#' background colors for the parent element \code{table} and the following -#' child elements: \code{heading}, \code{columns}, \code{row_group}, -#' \code{summary_row}, and \code{table_body}. A color name or a hexadecimal -#' color code should be provided. +#' background colors for the parent element `table` and the following child +#' elements: `heading`, `columns`, `row_group`, `summary_row`, and +#' `table_body`. A color name or a hexadecimal color code should be provided. #' @param table.border.top.style,table.border.top.width,table.border.top.color -#' the style, width, and color of the table's top border. +#' The style, width, and color of the table's top border. #' @param heading.border.bottom.style,heading.border.bottom.width,heading.border.bottom.color -#' the style, width, and color of the heading's bottom border. +#' The style, width, and color of the heading's bottom border. #' @param row_group.border.top.style,row_group.border.top.width,row_group.border.top.color -#' the style, width, and color of the row group's top border. +#' The style, width, and color of the row group's top border. #' @param row_group.border.bottom.style,row_group.border.bottom.width,row_group.border.bottom.color -#' the style, width, and color of the row group's bottom border. +#' The style, width, and color of the row group's bottom border. #' @param table_body.border.top.style,table_body.border.top.width,table_body.border.top.color -#' the style, width, and color of the table body's top border. +#' The style, width, and color of the table body's top border. #' @param table_body.border.bottom.style,table_body.border.bottom.width,table_body.border.bottom.color #' the style, width, and color of the table body's bottom border. #' @param row.padding,summary_row.padding,grand_summary_row.padding the amount #' of padding in each row and in each type of summary row. #' @param footnote.sep the separating characters between adjacent footnotes in #' the footnotes section. The default value produces a linebreak. -#' @param footnote.glyph the set of sequential figures or characters used to -#' identify the footnotes. We can either supply the keyword \code{"numbers"} -#' (the default, indicating that we want numeric glyphs), the keywords -#' \code{"letters"} or \code{"LETTERS"} (indicating that we want letters as -#' glyphs, either lowercase or uppercase), or, a vector of character values -#' representing the series of glyphs. A series of glyphs is recycled when its -#' usage goes beyond the length of the set. At each cycle, the glyphs are -#' simply combined (e.g., \code{*} -> \code{**} -> \code{***}). -#' @param footnote.padding,sourcenote.padding the amount of padding to apply to +#' @param footnote.glyph The set of sequential figures or characters used to +#' identify the footnotes. We can either supply the keyword `"numbers"` (the +#' default, indicating that we want numeric glyphs), the keywords `"letters"` +#' or `"LETTERS"` (indicating that we want letters as glyphs, either lowercase +#' or uppercase), or, a vector of character values representing the series of +#' glyphs. A series of glyphs is recycled when its usage goes beyond the +#' length of the set. At each cycle, the glyphs are simply combined (e.g., `*` +#' -> `**` -> `***`). +#' @param footnote.padding,sourcenote.padding The amount of padding to apply to #' the footnote and source note sections. -#' @param row.striping.include_stub an option for whether to include the stub +#' @param row.striping.include_stub An option for whether to include the stub #' when striping rows. -#' @param row.striping.include_table_body an option for whether to include the +#' @param row.striping.include_table_body An option for whether to include the #' table body when striping rows. -#' @param column_labels.hidden an option to hide the column labels. -#' @return an object of class \code{gt_tbl}. +#' @param column_labels.hidden An option to hide the column labels. +#' @return an object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table with #' # all the main parts added; we can use this diff --git a/R/tab_style.R b/R/tab_style.R index f73ecea785..1801ec9f08 100644 --- a/R/tab_style.R +++ b/R/tab_style.R @@ -1,45 +1,45 @@ #' Add custom styles to one or more cells #' -#' With the \code{tab_style()} function we can target specific cells and apply +#' With the `tab_style()` function we can target specific cells and apply #' styles to them. This is best done in conjunction with the -#' \code{\link{cells_styles}()} helper function. At present this function is +#' [cells_styles()] helper function. At present this function is #' focused on the application of styles for HTML output only (as such, other -#' output formats will ignore all \code{tab_style()} calls). With the help of -#' \code{\link{cells_styles}()}, we can set the following styles: +#' output formats will ignore all `tab_style()` calls). With the help of +#' [cells_styles()], we can set the following styles: #' \itemize{ -#' \item the background color of the cell (\code{bkgd_color}) -#' \item the cell's text color (\code{text_color}), font (\code{text_font}), or -#' size (\code{text_size}) -#' \item the text style (\code{text_style}), enabling the use of italics or +#' \item the background color of the cell (`bkgd_color`) +#' \item the cell's text color (`text_color`), font (`text_font`), or +#' size (`text_size`) +#' \item the text style (`text_style`), enabling the use of italics or #' oblique text. -#' \item text decoration (\code{text_decorate}): use overlines, line-throughs, +#' \item text decoration (`text_decorate`): use overlines, line-throughs, #' or underlines -#' \item text transformations (\code{text_transform}) that result in lowercased, +#' \item text transformations (`text_transform`) that result in lowercased, #' uppercased, or capitalized text -#' \item the text weight (\code{text_weight}), allowing the use of thin to +#' \item the text weight (`text_weight`), allowing the use of thin to #' bold text (the degree of choice is greater with variable fonts) -#' \item the alignment of text (\code{text_align}) +#' \item the alignment of text (`text_align`) #' \item a stretching property for text that condenses or expands text -#' (\code{text_stretch}) -#' \item the text indentation (\code{text_indent}) +#' (`text_stretch`) +#' \item the text indentation (`text_indent`) #' } #' #' @inheritParams fmt_number -#' @param style a vector of styles to use. The \code{\link{cells_styles}()} +#' @param style a vector of styles to use. The [cells_styles()] #' helper function can be used here to more easily generate valid styles. #' @param locations the cell or set of cells to be associated with the style -#' Supplying any of the \code{cells_*()} helper functions is a useful way to +#' Supplying any of the `cells_*()` helper functions is a useful way to #' target the location cells that are associated with the style application. -#' These helper functions are: \code{\link{cells_title}()}, -#' \code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -#' \code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -#' \code{\link{cells_summary}()}. Please see the help article +#' These helper functions are: [cells_title()], +#' [cells_column_labels()], [cells_group()], +#' [cells_stub()], [cells_data()], and +#' [cells_summary()]. Please see the help article #' \link{location_cells} for more information on how these helper functions -#' can be used. Additionally, we can enclose several \code{cells_*()} calls -#' within a \code{list()} if we wish to apply styles to different types of +#' can be used. Additionally, we can enclose several `cells_*()` calls +#' within a `list()` if we wish to apply styles to different types of #' locations (e.g., cell data values, stub group headings, the table title, #' etc.). -#' @return an object of class \code{gt_tbl}. +#' @return an object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # add styles that are to be applied @@ -101,8 +101,8 @@ #' \if{html}{\figure{man_tab_style_2.svg}{options: width=100\%}} #' #' @family table-part creation/modification functions -#' @seealso \code{\link{cells_styles}()} as a helper for defining custom styles -#' and \code{\link{cells_data}()} as a useful helper function for targeting +#' @seealso [cells_styles()] as a helper for defining custom styles +#' and [cells_data()] as a useful helper function for targeting #' one or more data cells to be styled. #' @importFrom stats setNames #' @export diff --git a/R/table_parts.R b/R/table_parts.R index 638e3a14e0..d4b29106f7 100644 --- a/R/table_parts.R +++ b/R/table_parts.R @@ -6,11 +6,11 @@ #' header's title and subtitle. Furthermore, if the table is intended for HTML #' output, we can use HTML in either of the title or subtitle. #' @inheritParams fmt_number -#' @param title,subtitle text to be used in the table title and, optionally, for -#' the table subtitle. We can elect to use the \code{\link{md}()} and -#' \code{\link{html}()} helper functions to style the text as Markdown or to -#' retain HTML elements in the text. -#' @return an object of class \code{gt_tbl}. +#' @param title,subtitle Text to be used in the table title and, optionally, for +#' the table subtitle. We can elect to use the [md()] and [html()] helper +#' functions to style the text as Markdown or to retain HTML elements in the +#' text. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table; #' # add a header part to contain a title @@ -56,10 +56,10 @@ tab_header <- function(data, #' Markdown formatting for the stubhead label. Furthermore, if the table is #' intended for HTML output, we can use HTML for the stubhead label. #' @inheritParams fmt_number -#' @param label the text to be used as the stubhead label We can optionally -#' use the \code{\link{md}()} and \code{\link{html}()} functions to style the -#' text as Markdown or to retain HTML elements in the text. -#' @return an object of class \code{gt_tbl}. +#' @param label The text to be used as the stubhead label We can optionally use +#' the [md()] and [html()] functions to style the text as Markdown or to +#' retain HTML elements in the text. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table; add #' # a stubhead label to describe what is @@ -89,25 +89,24 @@ tab_stubhead_label <- function(data, #' #' Create a row group with a collection of rows. This requires specification of #' the rows to be included, either by supplying row labels, row indices, or -#' through use of a select helper function like \code{starts_with()}. +#' through use of a select helper function like `starts_with()`. #' @inheritParams fmt_number -#' @param group the name of the row group. This text will also serve as the row +#' @param group The name of the row group. This text will also serve as the row #' group label. -#' @param rows the rows to be made components of the row group. Can either be a -#' vector of row captions provided \code{c()}, a vector of row indices, or a -#' helper function focused on selections. The select helper functions are: -#' \code{\link{starts_with}()}, \code{\link{ends_with}()}, -#' \code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -#' and \code{\link{everything}()}. -#' @param others an option to set a default row group label for any rows not -#' formally placed in a row group named by \code{group} in any call of -#' \code{tab_row_group()}. A separate call to \code{tab_row_group()} with only -#' a value to \code{others} is possible and makes explicit that the call is -#' meant to provide a default row group label. If this is not set and -#' there are rows that haven't been placed into a row group (where one or -#' more row groups already exist), those rows will be automatically placed into -#' a row group without a label. -#' @return an object of class \code{gt_tbl}. +#' @param rows The rows to be made components of the row group. Can either be a +#' vector of row captions provided `c()`, a vector of row indices, or a helper +#' function focused on selections. The select helper functions are: +#' [starts_with()], [ends_with()], [contains()], [matches()], [one_of()], and +#' [everything()]. +#' @param others An option to set a default row group label for any rows not +#' formally placed in a row group named by `group` in any call of +#' `tab_row_group()`. A separate call to `tab_row_group()` with only a value +#' to `others` is possible and makes explicit that the call is meant to +#' provide a default row group label. If this is not set and there are rows +#' that haven't been placed into a row group (where one or more row groups +#' already exist), those rows will be automatically placed into a row group +#' without a label. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table and #' # add two row groups with the labels: @@ -222,12 +221,12 @@ tab_row_group <- function(data, #' This label is placed above one or more column labels, spanning the width of #' those columns and column labels. #' @inheritParams fmt_number -#' @param label the text to use for the spanner column label. -#' @param columns the columns to be components of the spanner heading. -#' @param gather an option to move the specified \code{columns} such that they -#' are unified under the spanner column label. Ordering of the -#' moved-into-place columns will be preserved in all cases. -#' @return an object of class \code{gt_tbl}. +#' @param label The text to use for the spanner column label. +#' @param columns The columns to be components of the spanner heading. +#' @param gather An option to move the specified `columns` such that they are +#' unified under the spanner column label. Ordering of the moved-into-place +#' columns will be preserved in all cases. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table; #' # Group several columns related to car @@ -311,15 +310,14 @@ tab_spanner <- function(data, #' #' Add a source note to the footer part of the \pkg{gt} table. A source note is #' useful for citing the data included in the table. Several can be added to the -#' footer, simply use multiple calls of \code{tab_source_note()} and they will -#' be inserted in the order provided. We can use Markdown formatting for the -#' note, or, if the table is intended for HTML output, we can include HTML -#' formatting. +#' footer, simply use multiple calls of `tab_source_note()` and they will be +#' inserted in the order provided. We can use Markdown formatting for the note, +#' or, if the table is intended for HTML output, we can include HTML formatting. #' @inheritParams fmt_number -#' @param source_note text to be used in the source note. We can optionally use -#' the \code{\link{md}()} and \code{\link{html}()} functions to style the text -#' as Markdown or to retain HTML elements in the text. -#' @return an object of class \code{gt_tbl}. +#' @param source_note Text to be used in the source note. We can optionally use +#' the [md()] and [html()] functions to style the text as Markdown or to +#' retain HTML elements in the text. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `gtcars` to create a gt table; #' # add a source note to the table diff --git a/R/text_transform.R b/R/text_transform.R index d92504d515..44165f508c 100644 --- a/R/text_transform.R +++ b/R/text_transform.R @@ -1,19 +1,17 @@ #' Perform targeted text transformation with a function #' @inheritParams cols_align -#' @param locations the cell or set of cells to be associated with the text -#' transformation. Supplying any of the \code{cells_*()} helper functions is a +#' @param locations The cell or set of cells to be associated with the text +#' transformation. Supplying any of the `cells_*()` helper functions is a #' useful way to target the location cells that are associated with the -#' footnote text. These helper functions are: \code{\link{cells_title}()}, -#' \code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -#' \code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -#' \code{\link{cells_summary}()}. Please see the help article -#' \link{location_cells} for more information on how these helper functions -#' can be used. Additionally, we can enclose several \code{cells_*()} calls -#' within a \code{list()} if we wish to link the footnote text to different -#' types of locations (e.g., cell data values, stub group headings, the table -#' title, etc.). -#' @param fn the function to use for text transformation. -#' @return an object of class \code{gt_tbl}. +#' footnote text. These helper functions are: [cells_title()], +#' [cells_column_labels()], [cells_group()], [cells_stub()], [cells_data()], +#' and [cells_summary()]. Please see the help article \link{location_cells} +#' for more information on how these helper functions can be used. +#' Additionally, we can enclose several `cells_*()` calls within a `list()` if +#' we wish to link the footnote text to different types of locations (e.g., +#' cell data values, stub group headings, the table title, etc.). +#' @param fn The function to use for text transformation. +#' @return An object of class `gt_tbl`. #' @examples #' # Use `exibble` to create a gt table; #' # transform the formatted text in the diff --git a/R/utils.R b/R/utils.R index 74c7178599..599a5e317c 100644 --- a/R/utils.R +++ b/R/utils.R @@ -180,7 +180,7 @@ get_currency_exponent <- function(currency) { #' helper function), then the text will be sanitized and transformed to HTML #' from Markdown. If the incoming text has the class `html` (applied by `html()` #' helper function), then the text will be seen as HTML and it won't undergo -#' sanitization +#' sanitization. #' @importFrom stringr str_replace_all #' @importFrom htmltools htmlEscape #' @importFrom commonmark markdown_html @@ -277,7 +277,7 @@ process_text <- function(text, #' Reverse HTML escaping #' #' Find common HTML entities resulting from HTML escaping and restore them back -#' to ASCII characters +#' to ASCII characters. #' @noRd unescape_html <- function(text) { @@ -365,17 +365,17 @@ markdown_to_text <- function(text) { unname() } -#' Handle formatting of a pattern in a \code{fmt_*()} function +#' Handle formatting of a pattern in a `fmt_*()` function #' -#' Within the context of a \code{fmt_*()} function, we always have the -#' single-length character vector of \code{pattern} available to describe a -#' final decoration of the formatted values. We use \pkg{glue}'s semantics here -#' and reserve \code{x} to be the formatted values, and, we can use \code{x} +#' Within the context of a `fmt_*()`` function, we always have the +#' single-length character vector of `pattern` available to describe a +#' final decoration of the formatted values. We use glue's semantics here +#' and reserve `x` to be the formatted values, and, we can use `x` #' multiple times in the pattern. #' @param values The values (as a character vector) that are formatted within -#' the \code{fmt_*()} function. +#' the `fmt_*()` function. #' @param pattern A formatting pattern that allows for decoration of the -#' formatted value (defined here as \code{x}). +#' formatted value (defined here as `x`). #' @noRd apply_pattern_fmt_x <- function(values, pattern) { @@ -452,7 +452,7 @@ non_na_index <- function(values, #' #' The `num_suffix()` function operates on a vector of numerical values and #' returns a tibble where each row represents a scaled value for `x` and the -#' correct suffix to use during `x`'s character-based formatting +#' correct suffix to use during `x`'s character-based formatting. #' @importFrom dplyr tibble #' @noRd num_suffix <- function(x, @@ -540,7 +540,7 @@ is_false = function(x) { #' #' This function normalizes the `suffixing` input to a character vector which is #' later appended to scaled numerical values; the input can either be a single -#' logical value or a character vector +#' logical value or a character vector. #' @param suffixing,scale_by The `suffixing` and `scale_by` options in some #' `fmt_*()` functions. #' @noRd @@ -914,8 +914,7 @@ footnote_glyphs <- function(x, #' Determine whether an object is a `gt_tbl` #' -#' @param data A table object that is created using the \code{\link{gt}()} -#' function. +#' @param data A table object that is created using the [gt()] function. #' @importFrom checkmate test_class #' @noRd is_gt <- function(data) { @@ -925,8 +924,7 @@ is_gt <- function(data) { #' Stop any function if object is not a `gt_tbl` object #' -#' @param data A table object that is created using the \code{\link{gt}()} -#' function. +#' @param data A table object that is created using the [gt()] function. #' @noRd stop_if_not_gt <- function(data) { diff --git a/R/zzz.R b/R/zzz.R index d8a042d1d9..6fcda7ab59 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -84,10 +84,10 @@ globalVariables( #' #' @section Package options: #' -#' \pkg{gt} uses the following \code{\link{options}} to configure behavior: +#' \pkg{gt} uses the following [options()] to configure behavior: #' #' \itemize{ -#' \item \code{gt.stub_group.sep}: a separator between groups for the +#' \item `gt.stub_group.sep`: a separator between groups for the #' stub group label. #' #' } diff --git a/man/adjust_luminance.Rd b/man/adjust_luminance.Rd index 46be69dede..4c4f044f3e 100644 --- a/man/adjust_luminance.Rd +++ b/man/adjust_luminance.Rd @@ -7,12 +7,12 @@ adjust_luminance(colors, steps) } \arguments{ -\item{colors}{a vector of colors that will undergo an adjustment in +\item{colors}{A vector of colors that will undergo an adjustment in luminance. Each color value provided must either be a color name (in the -set of colors provided by \code{grDevices::colors()}) or a hexadecimal -string in the form of "#RRGGBB" or "#RRGGBBAA".} +set of colors provided by \code{grDevices::colors()}) or a hexadecimal string in +the form of "#RRGGBB" or "#RRGGBBAA".} -\item{steps}{a positive or negative factor by which the luminance will be +\item{steps}{A positive or negative factor by which the luminance will be adjusted. Must be a number between \code{-2.0} and \code{2.0}.} } \description{ @@ -23,10 +23,10 @@ apply greater darkening or lightening for those colors in the midrange compared to any very dark or very light colors in the input palette. } \details{ -This function can be useful when combined with the \code{\link{data_color}()} -function's \code{palette} argument, which can use a vector of colors or any -of the \code{col_*} functions from the \pkg{scales} package (all of which -have a \code{palette} argument). +This function can be useful when combined with the \code{\link[=data_color]{data_color()}} function's +\code{palette} argument, which can use a vector of colors or any of the \code{col_*} +functions from the \pkg{scales} package (all of which have a \code{palette} +argument). } \section{Figures}{ diff --git a/man/as_latex.Rd b/man/as_latex.Rd index ecc4def5e9..657b7143ad 100644 --- a/man/as_latex.Rd +++ b/man/as_latex.Rd @@ -7,15 +7,14 @@ as_latex(data) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} } \description{ -Get the LaTeX content from a \code{gt_tbl} object as a \code{knit_asis} -object. This object contains the LaTeX code and attributes that serve as -LaTeX dependencies (i.e., the LaTeX packages required for the table). Using -\code{as.character()} on the created object will result in a single-element -vector containing the LaTeX code. +Get the LaTeX content from a \code{gt_tbl} object as a \code{knit_asis} object. This +object contains the LaTeX code and attributes that serve as LaTeX +dependencies (i.e., the LaTeX packages required for the table). Using +\code{as.character()} on the created object will result in a single-element vector +containing the LaTeX code. } \examples{ # Use `gtcars` to create a gt table; diff --git a/man/as_raw_html.Rd b/man/as_raw_html.Rd index e212622572..bbefd72e2d 100644 --- a/man/as_raw_html.Rd +++ b/man/as_raw_html.Rd @@ -7,19 +7,18 @@ as_raw_html(data, inline_css = TRUE) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{inline_css}{an option to supply styles to table elements as inlined CSS +\item{inline_css}{An option to supply styles to table elements as inlined CSS styles.} } \description{ -Get the HTML content from a \code{gt_tbl} object as a single-element -character vector. By default, the generated HTML will have inlined styles, -where CSS styles (that were previously contained in CSS rule sets external to -the \code{
element}) are included as \code{style} attributes in the -HTML table's tags. This option is preferable when using the output HTML table -in an emailing context. +Get the HTML content from a \code{gt_tbl} object as a single-element character +vector. By default, the generated HTML will have inlined styles, where CSS +styles (that were previously contained in CSS rule sets external to the +\code{
element}) are included as \code{style} attributes in the HTML table's +tags. This option is preferable when using the output HTML table in an +emailing context. } \examples{ # Use `gtcars` to create a gt table; diff --git a/man/as_rtf.Rd b/man/as_rtf.Rd index 28d5d07359..276fb01460 100644 --- a/man/as_rtf.Rd +++ b/man/as_rtf.Rd @@ -10,9 +10,9 @@ as_rtf(data) \item{data}{a table object that is created using the \code{gt()} function.} } \description{ -Get the RTF content from a \code{gt_tbl} object as as a single-element -character vector. This object can be used with \code{writeLines()} to -generate a valid .rtf file that can be opened by RTF readers. +Get the RTF content from a \code{gt_tbl} object as as a single-element character +vector. This object can be used with \code{writeLines()} to generate a valid .rtf +file that can be opened by RTF readers. } \examples{ # Use `gtcars` to create a gt table; diff --git a/man/cells_styles.Rd b/man/cells_styles.Rd index 2c057d0337..41fd56ae95 100644 --- a/man/cells_styles.Rd +++ b/man/cells_styles.Rd @@ -10,56 +10,53 @@ cells_styles(bkgd_color = NULL, text_color = NULL, text_font = NULL, text_decorate = NULL, text_transform = NULL) } \arguments{ -\item{bkgd_color}{the background color of the cell.} +\item{bkgd_color}{The background color of the cell.} -\item{text_color}{the text color.} +\item{text_color}{The text color.} -\item{text_font}{the font or collection of fonts (subsequent font names are) +\item{text_font}{The font or collection of fonts (subsequent font names are) used as fallbacks.} -\item{text_size}{the size of the font. Can be provided as a number that is -assumed to represent \code{px} values (or could be wrapped in the -\code{\link{px}()}) helper function. We can also use one of the following -absolute size keywords: \code{xx-small}, \code{x-small}, \code{small}, -\code{medium}, \code{large}, \code{x-large}, or \code{xx-large}.} +\item{text_size}{The size of the font. Can be provided as a number that is +assumed to represent \code{px} values (or could be wrapped in the \code{\link[=px]{px()}}) helper +function. We can also use one of the following absolute size keywords: +\code{xx-small}, \code{x-small}, \code{small}, \code{medium}, \code{large}, \code{x-large}, or +\code{xx-large}.} -\item{text_align}{the text alignment. Can be one of either \code{"center"}, +\item{text_align}{The text alignment. Can be one of either \code{"center"}, \code{"left"}, \code{"right"}, or \code{"justify"}.} -\item{text_style}{the text style. Can be one of either \code{"center"}, +\item{text_style}{The text style. Can be one of either \code{"center"}, \code{"normal"}, \code{"italic"}, or \code{"oblique"}.} -\item{text_weight}{the weight of the font. Can be a text-based keyword such -as \code{"normal"}, \code{"bold"}, \code{"lighter"}, \code{"bolder"}, or, a -numeric value between \code{1} and \code{1000}, inclusive. Note that only -variable fonts may support the numeric mapping of weight.} +\item{text_weight}{The weight of the font. Can be a text-based keyword such +as \code{"normal"}, \code{"bold"}, \code{"lighter"}, \code{"bolder"}, or, a numeric value +between \code{1} and \code{1000}, inclusive. Note that only variable fonts may +support the numeric mapping of weight.} -\item{text_stretch}{allows for text to either be condensed or expanded. We +\item{text_stretch}{Allows for text to either be condensed or expanded. We can use the following text-based keywords to describe the degree of -condensation/expansion: \code{ultra-condensed}, \code{extra-condensed}, -\code{condensed}, \code{semi-condensed}, \code{normal}, -\code{semi-expanded}, \code{expanded}, \code{extra-expanded}, and -\code{ultra-expanded}. Alternatively, we can supply percentage values from -\code{0\%} to \code{200\%}, inclusive. Negative percentage values are not -allowed.} +condensation/expansion: \code{ultra-condensed}, \code{extra-condensed}, \code{condensed}, +\code{semi-condensed}, \code{normal}, \code{semi-expanded}, \code{expanded}, \code{extra-expanded}, +and \code{ultra-expanded}. Alternatively, we can supply percentage values from +\code{0\\\%} to \code{200\\\%}, inclusive. Negative percentage values are not allowed.} -\item{text_indent}{the indentation of the text.} +\item{text_indent}{The indentation of the text.} -\item{text_decorate}{allows for text decoration effect to be applied. Here, +\item{text_decorate}{Allows for text decoration effect to be applied. Here, we can use \code{"overline"}, \code{"line-through"}, or \code{"underline"}.} -\item{text_transform}{allows for the transformation of text. Options are +\item{text_transform}{Allows for the transformation of text. Options are \code{"uppercase"}, \code{"lowercase"}, or \code{"capitalize"}.} } \value{ -a character vector containing formatted styles. +A character vector containing formatted styles. } \description{ -This helper function is to be used with the \code{\link{tab_style}()} -function, which itself allows for the setting of custom styles to one or more -cells. We can also define several styles within a single call of -\code{cells_styles} and \code{\link{tab_style}()} will reliably apply those -styles to the targeted element. +This helper function is to be used with the \code{\link[=tab_style]{tab_style()}} function, which +itself allows for the setting of custom styles to one or more cells. We can +also define several styles within a single call of \code{cells_styles} and +\code{\link[=tab_style]{tab_style()}} will reliably apply those styles to the targeted element. } \seealso{ Other helper functions: \code{\link{escape_latex}}, diff --git a/man/cols_align.Rd b/man/cols_align.Rd index 7b6ee7be62..e63fa3856d 100644 --- a/man/cols_align.Rd +++ b/man/cols_align.Rd @@ -8,36 +8,34 @@ cols_align(data, align = c("auto", "left", "center", "right"), columns = TRUE) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{align}{the alignment type. This can be any of \code{"center"}, -\code{"left"}, or \code{"right"} for center-, left-, or center-alignment. -Alternatively, the \code{"auto"} option (the default), will automatically -align values in columns according to the data type (see the Details section -for specifics on which alignments are applied).} +\item{align}{The alignment type. This can be any of \code{"center"}, \code{"left"}, or +\code{"right"} for center-, left-, or center-alignment. Alternatively, the +\code{"auto"} option (the default), will automatically align values in columns +according to the data type (see the Details section for specifics on which +alignments are applied).} -\item{columns}{an optional vector of column names for which the alignment -should be applied. If nothing is supplied, or if \code{columns} is -\code{TRUE}), then the chosen alignment affects all columns.} +\item{columns}{An optional vector of column names for which the alignment +should be applied. If nothing is supplied, or if \code{columns} is \code{TRUE}), then +the chosen alignment affects all columns.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The individual alignments of columns (which includes the column labels and all of their data cells) can be modified. We have the option to align text to -the \code{left}, the \code{center}, and the \code{right}. In a less explicit -manner, we can allow \pkg{gt} to automatically choose the alignment of each -column based on the data type (with the \code{auto} option). +the \code{left}, the \code{center}, and the \code{right}. In a less explicit manner, we can +allow \pkg{gt} to automatically choose the alignment of each column based on +the data type (with the \code{auto} option). } \details{ -When you create a \pkg{gt} table object using \code{\link{gt}()}, automatic -alignment of column labels and their data cells is performed. By default, -left-alignment is applied to columns of class \code{character}, \code{Date}, -or \code{POSIXct}; center-alignment is for columns of class \code{logical}, -\code{factor}, or \code{list}; and right-alignment is used for the -\code{numeric} and \code{integer} columns. +When you create a \pkg{gt} table object using \code{\link[=gt]{gt()}}, automatic alignment of +column labels and their data cells is performed. By default, left-alignment +is applied to columns of class \code{character}, \code{Date}, or \code{POSIXct}; +center-alignment is for columns of class \code{logical}, \code{factor}, or \code{list}; and +right-alignment is used for the \code{numeric} and \code{integer} columns. } \section{Figures}{ diff --git a/man/cols_hide.Rd b/man/cols_hide.Rd index 0f901a8421..87820e3031 100644 --- a/man/cols_hide.Rd +++ b/man/cols_hide.Rd @@ -7,32 +7,31 @@ cols_hide(data, columns) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{columns}{the column names to hide from the output display table. The +\item{columns}{The column names to hide from the output display table. The order of the remaining columns will be preserved. Values provided that do not correspond to column names will be disregarded.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The \code{cols_hide()} function allows us to hide one or more columns from appearing in the final output table. While it's possible and often desirable -to omit columns from the input table data before introduction to the -\code{\link{gt}()} function, there can be cases where the data in certain -columns is useful (as a column reference during formatting of other columns) -but the final display of those columns is not necessary. +to omit columns from the input table data before introduction to the \code{\link[=gt]{gt()}} +function, there can be cases where the data in certain columns is useful (as +a column reference during formatting of other columns) but the final display +of those columns is not necessary. } \details{ The hiding of columns is internally a rendering directive, so, all columns that are 'hidden' are still accessible and useful in any expression provided -to a \code{rows} argument. Furthermore, the \code{cols_hide()} function (as -with many \pkg{gt} functions) can be placed anywhere in a pipeline of -\pkg{gt} function calls (acting as a promise to hide columns when the timing -is right). However there's perhaps greater readability when placing this call -closer to the end of such a pipeline. +to a \code{rows} argument. Furthermore, the \code{cols_hide()} function (as with many +\pkg{gt} functions) can be placed anywhere in a pipeline of \pkg{gt} function +calls (acting as a promise to hide columns when the timing is right). However +there's perhaps greater readability when placing this call closer to the end +of such a pipeline. } \section{Figures}{ diff --git a/man/cols_label.Rd b/man/cols_label.Rd index a38ddd878e..d252a01aea 100644 --- a/man/cols_label.Rd +++ b/man/cols_label.Rd @@ -7,34 +7,34 @@ cols_label(data, ..., .list = list2(...)) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{...}{one or more named arguments of column names from the input `data` +\item{...}{One or more named arguments of column names from the input \code{data} table along with their labels for display as the column labels. We can -optionally wrap the column labels with \code{\link{md}()} (to interpret -text as Markdown) or \code{\link{html}()} (to interpret text as HTML).} +optionally wrap the column labels with \code{\link[=md]{md()}} (to interpret text as +Markdown) or \code{\link[=html]{html()}} (to interpret text as HTML).} -\item{.list}{allows for the use of a list as an input alternative to -\code{...}.} +\item{.list}{Allows for the use of a list as an input alternative to \code{...}.} +} +\value{ +An object of class \code{gt_tbl}. } \description{ Column labels can be modified from their default values (the names of the columns from the input table data). When you create a \pkg{gt} table object -using \code{\link{gt}()}, column names effectively become the column labels. -While this serves as a good first approximation, column names aren't often -appealing as column labels in a \pkg{gt} output table. The -\code{cols_label()} function provides the flexibility to relabel one or more -columns and we even have the option to use the \code{\link{md}()} or -\code{\link{html}()} helper functions for rendering column labels from -Markdown or using HTML. +using \code{\link[=gt]{gt()}}, column names effectively become the column labels. While this +serves as a good first approximation, column names aren't often appealing as +column labels in a \pkg{gt} output table. The \code{cols_label()} function +provides the flexibility to relabel one or more columns and we even have the +option to use the \code{\link[=md]{md()}} or \code{\link[=html]{html()}} helper functions for rendering column +labels from Markdown or using HTML. } \details{ It's important to note that while columns can be freely relabeled, we continue to refer to columns by their original column names. Column names in -a tibble or data frame must be unique whereas column labels in \pkg{gt} -have no requirement for uniqueness (which is useful for labeling columns as, -say, measurement units that may be repeated several times---usually under +a tibble or data frame must be unique whereas column labels in \pkg{gt} have +no requirement for uniqueness (which is useful for labeling columns as, say, +measurement units that may be repeated several times---usually under different spanner column labels). Thus, we can still easily distinguish between columns in other \pkg{gt} function calls (e.g., in all of the \code{fmt*()} functions) even though we may lose distinguishability in column diff --git a/man/cols_merge.Rd b/man/cols_merge.Rd index 77dec50ff9..498610919b 100644 --- a/man/cols_merge.Rd +++ b/man/cols_merge.Rd @@ -7,41 +7,39 @@ cols_merge(data, col_1, col_2, pattern = "{1} {2}") } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{col_1}{a retained column that contains values to be merged with those +\item{col_1}{A retained column that contains values to be merged with those in \code{col_2}.} -\item{col_2}{a column that contains values to be merged with those in -\code{col_1}. This column will be discarded but is still useful as a -reference in other \pkg{gt} functions.} +\item{col_2}{A column that contains values to be merged with those in +\code{col_1}. This column will be discarded but is still useful as a reference +in other \pkg{gt} functions.} -\item{pattern}{a formatting pattern that specifies the arrangement of the -\code{col_1} and \code{col_1} values and any string literals. The -\code{col_1} column is represented as \code{{1}} whereas \code{col_2} is -\code{{2}}. All other characters are taken to be string literals.} +\item{pattern}{A formatting pattern that specifies the arrangement of the +\code{col_1} and \code{col_1} values and any string literals. The \code{col_1} column is +represented as \code{{1}} whereas \code{col_2} is \code{{2}}. All other characters are +taken to be string literals.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ This function takes any two columns and merges them into a single column, using a pattern that specifies how the values in the data cells are combined. -We specify the columns to merge together in the \code{col_1} and \code{col_2} -arguments and the string-combining pattern is specified in \code{pattern}. -The column that is retained is that of \code{col_1} whereas the column -specified in \code{col_2} is dropped from the output table. +We specify the columns to merge together in the \code{col_1} and \code{col_2} arguments +and the string-combining pattern is specified in \code{pattern}. The column that +is retained is that of \code{col_1} whereas the column specified in \code{col_2} is +dropped from the output table. } \details{ There are two other column-merging functions that offer specialized behavior -that is optimized for common table tasks: \code{\link{cols_merge_range}()} -and \code{\link{cols_merge_uncert}()}. These functions operate similarly, -where the second column specified is dropped from the output table. For all -of the \code{cols_merge*()} functions, column removal occurs late in the -rendering lifecycle so those secondary columns are still usable as column -references (e.g., inside expressions provided to `rows` in the \code{fmt*()} -functions). +that is optimized for common table tasks: \code{\link[=cols_merge_range]{cols_merge_range()}} and +\code{\link[=cols_merge_uncert]{cols_merge_uncert()}}. These functions operate similarly, where the second +column specified is dropped from the output table. For all of the +\code{cols_merge*()} functions, column removal occurs late in the rendering +lifecycle so those secondary columns are still usable as column references +(e.g., inside expressions provided to \code{rows} in the \code{fmt*()} functions). } \section{Figures}{ diff --git a/man/cols_merge_range.Rd b/man/cols_merge_range.Rd index c822f87fc4..b7781adb23 100644 --- a/man/cols_merge_range.Rd +++ b/man/cols_merge_range.Rd @@ -4,31 +4,30 @@ \alias{cols_merge_range} \title{Merge two columns to a value range column} \usage{ -cols_merge_range(data, col_begin, col_end) +cols_merge_range(data, col_begin, col_end, sep = "---") } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{col_begin}{a column that contains values for the start of the range.} +\item{col_begin}{A column that contains values for the start of the range.} -\item{col_end}{a column that contains values for the end of the range.} +\item{col_end}{A column that contains values for the end of the range.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The \code{cols_merge_range()} function is a specialized variant of the -\code{\link{cols_merge}()} function. It operates by taking a two columns that -constitute a range of values (\code{col_begin} and \code{col_end}) and merges -them into a single column. What results is a column containing both values -separated by a long dash (e.g., \code{12.0 — 20.0}). The column specified in -\code{col_end} is dropped from the output table. +\code{\link[=cols_merge]{cols_merge()}} function. It operates by taking a two columns that constitute +a range of values (\code{col_begin} and \code{col_end}) and merges them into a single +column. What results is a column containing both values separated by a long +dash (e.g., \code{12.0 — 20.0}). The column specified in \code{col_end} is dropped from +the output table. } \details{ -This function could be somewhat replicated using \code{\link{cols_merge}()}, -however, \code{cols_merge_range()} employs the following specialized -semantics for \code{NA} handling: +This function could be somewhat replicated using \code{\link[=cols_merge]{cols_merge()}}, however, +\code{cols_merge_range()} employs the following specialized semantics for \code{NA} +handling: \enumerate{ @@ -44,18 +43,16 @@ missing values for the merged column (e.g., \code{NA} + \code{NA} = \code{NA}) } -Any resulting \code{NA} values in the \code{col_begin} column following the -merge operation can be easily formatted using the \code{\link{fmt_missing}()} -function. +Any resulting \code{NA} values in the \code{col_begin} column following the merge +operation can be easily formatted using the \code{\link[=fmt_missing]{fmt_missing()}} function. This function is part of a set of three column-merging functions. The other -two are the general \code{\link{cols_merge}()} function and the specialized -\code{\link{cols_merge_uncert}()} function. These functions operate -similarly, where the second column specified is dropped from the output -table. For all of the \code{cols_merge*()} functions, column removal occurs -late in the rendering lifecycle so those secondary columns are still usable -as column references (e.g., inside expressions provided to `rows` in the -\code{fmt*()} functions). +two are the general \code{\link[=cols_merge]{cols_merge()}} function and the specialized +\code{\link[=cols_merge_uncert]{cols_merge_uncert()}} function. These functions operate similarly, where the +second column specified is dropped from the output table. For all of the +\code{cols_merge*()} functions, column removal occurs late in the rendering +lifecycle so those secondary columns are still usable as column references +(e.g., inside expressions provided to \code{rows} in the \code{fmt*()} functions). } \section{Figures}{ diff --git a/man/cols_merge_uncert.Rd b/man/cols_merge_uncert.Rd index 037b505fa4..814560019b 100644 --- a/man/cols_merge_uncert.Rd +++ b/man/cols_merge_uncert.Rd @@ -7,28 +7,27 @@ cols_merge_uncert(data, col_val, col_uncert) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{col_val}{a single column name that contains the base values.} +\item{col_val}{A single column name that contains the base values.} -\item{col_uncert}{a single column name that contains the uncertainty values.} +\item{col_uncert}{A single column name that contains the uncertainty values.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The \code{cols_merge_uncert()} function is a specialized variant of the -\code{\link{cols_merge}()} function. It operates by taking a base value -column (\code{col_val}) and an uncertainty column (\code{col_uncert}) and -merges them into a single column. What results is a column with values and -associated uncertainties (e.g., \code{12.0 ± 0.1}), and, the column specified -in \code{col_uncert} is dropped from the output table. +\code{\link[=cols_merge]{cols_merge()}} function. It operates by taking a base value column +(\code{col_val}) and an uncertainty column (\code{col_uncert}) and merges them into a +single column. What results is a column with values and associated +uncertainties (e.g., \code{12.0 ± 0.1}), and, the column specified in \code{col_uncert} +is dropped from the output table. } \details{ -This function could be somewhat replicated using \code{\link{cols_merge}()}, -however, \code{cols_merge_uncert()} employs the following specialized -semantics for \code{NA} handling: +This function could be somewhat replicated using \code{\link[=cols_merge]{cols_merge()}}, however, +\code{cols_merge_uncert()} employs the following specialized semantics for \code{NA} +handling: \enumerate{ @@ -44,18 +43,16 @@ missing values for the merged column (e.g., \code{NA} + \code{NA} = \code{NA}) } -Any resulting \code{NA} values in the \code{col_val} column following the -merge operation can be easily formatted using the \code{\link{fmt_missing}()} -function. +Any resulting \code{NA} values in the \code{col_val} column following the merge +operation can be easily formatted using the \code{\link[=fmt_missing]{fmt_missing()}} function. This function is part of a set of three column-merging functions. The other -two are the general \code{\link{cols_merge}()} function and the specialized -\code{\link{cols_merge_range}()} function. These functions operate similarly, -where the second column specified is dropped from the output table. For all -of the \code{cols_merge*()} functions, column removal occurs late in the -rendering lifecycle so those secondary columns are still usable as column -references (e.g., inside expressions provided to `rows` in the \code{fmt*()} -functions). +two are the general \code{\link[=cols_merge]{cols_merge()}} function and the specialized +\code{\link[=cols_merge_range]{cols_merge_range()}} function. These functions operate similarly, where the +second column specified is dropped from the output table. For all of the +\code{cols_merge*()} functions, column removal occurs late in the rendering +lifecycle so those secondary columns are still usable as column references +(e.g., inside expressions provided to \code{rows} in the \code{fmt*()} functions). } \section{Figures}{ diff --git a/man/cols_move.Rd b/man/cols_move.Rd index fab3ab31e5..7a75c44c5c 100644 --- a/man/cols_move.Rd +++ b/man/cols_move.Rd @@ -7,36 +7,34 @@ cols_move(data, columns, after) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{columns}{the column names to move to as a group to a different +\item{columns}{The column names to move to as a group to a different position. The order of the remaining columns will be preserved.} -\item{after}{a column name used to anchor the insertion of the moved columns. +\item{after}{A column name used to anchor the insertion of the moved columns. All of the moved columns will be placed to the right of this column.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ On those occasions where you need to move columns this way or that way, we -can make use of the \code{cols_move()} function. While it's true that the -movement of columns can be done upstream of \pkg{gt}'s API, it is much easier -and less error prone to use the function provided here. The movement -procedure here takes one or more specified columns (in the \code{columns} -argument) and places them to the right of a different column (the -\code{after} argument). The ordering of the \code{columns} to be moved is -preserved, as is the ordering of all other columns in the table. +can make use of the \code{cols_move()} function. While it's true that the movement +of columns can be done upstream of \pkg{gt}'s API, it is much easier and less +error prone to use the function provided here. The movement procedure here +takes one or more specified columns (in the \code{columns} argument) and places +them to the right of a different column (the \code{after} argument). The ordering +of the \code{columns} to be moved is preserved, as is the ordering of all other +columns in the table. } \details{ -The columns supplied in \code{columns} must all exist in the table and none -of them can be in the \code{after} argument. The \code{after} column must -also exist and only one column should be provided here. If you need to place -one or columns at the beginning of the column series, the -\code{\link{cols_move_to_start}()} function should be used. Similarly, if -those columns to move should be placed at the end of the column series then -use \code{\link{cols_move_to_end}()}. +The columns supplied in \code{columns} must all exist in the table and none of +them can be in the \code{after} argument. The \code{after} column must also exist and +only one column should be provided here. If you need to place one or columns +at the beginning of the column series, the \code{\link[=cols_move_to_start]{cols_move_to_start()}} function +should be used. Similarly, if those columns to move should be placed at the +end of the column series then use \code{\link[=cols_move_to_end]{cols_move_to_end()}}. } \section{Figures}{ diff --git a/man/cols_move_to_end.Rd b/man/cols_move_to_end.Rd index 02ec267f36..37131925ef 100644 --- a/man/cols_move_to_end.Rd +++ b/man/cols_move_to_end.Rd @@ -7,30 +7,28 @@ cols_move_to_end(data, columns) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{columns}{the column names to move to the right-most side of the table. +\item{columns}{The column names to move to the right-most side of the table. The order in which columns are provided will be preserved (as is the case with the remaining columns).} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ It's possible to move a set of columns to the end of the column series, we -only need to specify which \code{columns} are to be moved. While this can be -done upstream of \pkg{gt}'s API, this function makes to process much easier -and it's less error prone. The ordering of the \code{columns} that are moved -to the end is preserved (same with the ordering of all other columns in the -table). +only need to specify which \code{columns} are to be moved. While this can be done +upstream of \pkg{gt}'s API, this function makes to process much easier and +it's less error prone. The ordering of the \code{columns} that are moved to the +end is preserved (same with the ordering of all other columns in the table). } \details{ -The columns supplied in \code{columns} must all exist in the table. If you -need to place one or columns at the start of the column series, the -\code{\link{cols_move_to_start}()} function should be used. More control is -offered with the \code{\link{cols_move}()} function, where columns could be -placed after a specific column. +The columns supplied in \code{columns} must all exist in the table. If you need to +place one or columns at the start of the column series, the +\code{\link[=cols_move_to_start]{cols_move_to_start()}} function should be used. More control is offered with +the \code{\link[=cols_move]{cols_move()}} function, where columns could be placed after a specific +column. } \section{Figures}{ diff --git a/man/cols_move_to_start.Rd b/man/cols_move_to_start.Rd index 9d598395ac..91c6987a64 100644 --- a/man/cols_move_to_start.Rd +++ b/man/cols_move_to_start.Rd @@ -7,30 +7,29 @@ cols_move_to_start(data, columns) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{columns}{the column names to move to the left-most side of the table. +\item{columns}{The column names to move to the left-most side of the table. The order in which columns are provided will be preserved (as is the case with the remaining columns).} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ We can easily move set of columns to the beginning of the column series and -we only need to specify which \code{columns}. It's possible to do this -upstream of \pkg{gt}'s API, however, it is easier with this function and it -presents less possibility for error. The ordering of the \code{columns} that -are moved to the start is preserved (same with the ordering of all other -columns in the table). +we only need to specify which \code{columns}. It's possible to do this upstream of +\pkg{gt}'s API, however, it is easier with this function and it presents less +possibility for error. The ordering of the \code{columns} that are moved to the +start is preserved (same with the ordering of all other columns in the +table). } \details{ -The columns supplied in \code{columns} must all exist in the table. If you -need to place one or columns at the end of the column series, the -\code{\link{cols_move_to_end}()} function should be used. More control is -offered with the \code{\link{cols_move}()} function, where columns could be -placed after a specific column. +The columns supplied in \code{columns} must all exist in the table. If you need to +place one or columns at the end of the column series, the +\code{\link[=cols_move_to_end]{cols_move_to_end()}} function should be used. More control is offered with +the \code{\link[=cols_move]{cols_move()}} function, where columns could be placed after a specific +column. } \section{Figures}{ diff --git a/man/cols_split_delim.Rd b/man/cols_split_delim.Rd index 60ee95082a..4889862950 100644 --- a/man/cols_split_delim.Rd +++ b/man/cols_split_delim.Rd @@ -7,19 +7,18 @@ cols_split_delim(data, delim, columns = NULL) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{delim}{the delimiter to use to split an input column name. The +\item{delim}{The delimiter to use to split an input column name. The delimiter supplied will be autoescaped for the internal splitting procedure. The first component of the split will become the group name and the second component will be the column label.} -\item{columns}{an optional vector of column names that this operation should +\item{columns}{An optional vector of column names that this operation should be limited to. The default is to consider all columns in the table.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ This function will split selected delimited column names such that the first @@ -29,17 +28,16 @@ reference to individual columns must continue to be the column names from the input table data (which are unique by necessity). } \details{ -If we look to the column names in the \code{iris} dataset as an example of -how \code{cols_split_delim()} might be useful, we find the names -\code{Sepal.Length}, \code{Sepal.Width}, \code{Petal.Length}, -\code{Petal.Width}. From this naming system, it's easy to see that the -\code{Sepal} and \code{Petal} can group together the repeated common -\code{Length} and \code{Width} values. In your own datasets, we can avoid a -lengthy relabeling with \code{\link{cols_label}()} if column names can be -fashioned beforehand to contain both the spanner column label and the column -label. An additional advantage is that the column names in the input table -data remain unique even though there may eventually be repeated column labels -in the rendered output table). +If we look to the column names in the \code{iris} dataset as an example of how +\code{cols_split_delim()} might be useful, we find the names \code{Sepal.Length}, +\code{Sepal.Width}, \code{Petal.Length}, \code{Petal.Width}. From this naming system, it's +easy to see that the \code{Sepal} and \code{Petal} can group together the repeated +common \code{Length} and \code{Width} values. In your own datasets, we can avoid a +lengthy relabeling with \code{\link[=cols_label]{cols_label()}} if column names can be fashioned +beforehand to contain both the spanner column label and the column label. An +additional advantage is that the column names in the input table data remain +unique even though there may eventually be repeated column labels in the +rendered output table). } \section{Figures}{ diff --git a/man/countrypops.Rd b/man/countrypops.Rd index 6db177799a..ed61eaa095 100644 --- a/man/countrypops.Rd +++ b/man/countrypops.Rd @@ -6,11 +6,11 @@ \title{Yearly populations of countries from 1960 to 2017} \format{A tibble with 12470 rows and 5 variables: \describe{ - \item{country_name}{Name of the country} - \item{country_code_2}{The 2-letter ISO 3166-1 country code} - \item{country_code_3}{The 3-letter ISO 3166-1 country code} - \item{year}{The year for the population estimate} - \item{population}{The population estimate, midway through the year} +\item{country_name}{Name of the country} +\item{country_code_2}{The 2-letter ISO 3166-1 country code} +\item{country_code_3}{The 3-letter ISO 3166-1 country code} +\item{year}{The year for the population estimate} +\item{population}{The population estimate, midway through the year} }} \source{ \url{https://data.worldbank.org/indicator/SP.POP.TOTL} @@ -23,9 +23,8 @@ A dataset that presents yearly, total populations of countries. Total population is based on counts of all residents regardless of legal status or citizenship. Country identifiers include the English-language country names, and the 2- and 3-letter ISO 3166-1 country codes. Each row contains a -\code{population} value for a given \code{year} (from 1960 to 2017). Any -\code{NA} values for \code{populations} indicate the non-existence of the -country during that year. +\code{population} value for a given \code{year} (from 1960 to 2017). Any \code{NA} values +for \code{populations} indicate the non-existence of the country during that year. } \examples{ # Here is a glimpse at the data diff --git a/man/data_color.Rd b/man/data_color.Rd index 69e8d5c709..ab1be49495 100644 --- a/man/data_color.Rd +++ b/man/data_color.Rd @@ -8,12 +8,11 @@ data_color(data, columns, colors, alpha = NULL, apply_to = "bkgd", autocolor_text = TRUE) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{columns}{the columns wherein changes to cell data colors should occur.} +\item{columns}{The columns wherein changes to cell data colors should occur.} -\item{colors}{either a color mapping function from the \code{scales} package +\item{colors}{Either a color mapping function from the \code{scales} package or a vector of colors to use for each distinct value or level in each of the provided \code{columns}. The color mapping functions are: \code{scales::col_quantile()}, \code{scales::col_bin()}, @@ -22,51 +21,51 @@ a vector of colors as a palette, each color value provided must either be a color name (in the set of colors provided by \code{grDevices::colors()}) or a hexadecimal string in the form of "#RRGGBB" or "#RRGGBBAA".} -\item{alpha}{an optional, fixed alpha transparency value that will be applied +\item{alpha}{An optional, fixed alpha transparency value that will be applied to all of the \code{colors} provided if they are provided as a vector of colors. If using a colorizing helper function for \code{colors} then this option is ignored (each of the colorizing helper functions has its own \code{alpha} argument).} -\item{apply_to}{which style element should the colors be applied to? Options +\item{apply_to}{Which style element should the colors be applied to? Options include the cell background (the default, given as \code{bkgd}) or the cell text (\code{text}).} -\item{autocolor_text}{an option to let \pkg{gt} modify the coloring of text +\item{autocolor_text}{An option to let \pkg{gt} modify the coloring of text within cells undergoing background coloring. This will in some cases yield more optimal text-to-background color contrast. By default, this is set to \code{TRUE}.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ It's possible to add color to data cells according to their values. The -\code{data_color()} function colors all rows of any \code{columns} supplied. -There are two ways to define how cells are colored: (1) through the use of a -supplied color palette, and (2) through use of a color mapping function -available from the \code{scales} package. The first method colorizes cell -data according to whether values are character or numeric. The second method -provides more control over how cells are colored since we provide an explicit -color function and thus other requirements such as bin counts, cut points, or -a numeric domain. Finally, we can choose whether to apply the cell-specific +\code{data_color()} function colors all rows of any \code{columns} supplied. There are +two ways to define how cells are colored: (1) through the use of a supplied +color palette, and (2) through use of a color mapping function available from +the \code{scales} package. The first method colorizes cell data according to +whether values are character or numeric. The second method provides more +control over how cells are colored since we provide an explicit color +function and thus other requirements such as bin counts, cut points, or a +numeric domain. Finally, we can choose whether to apply the cell-specific colors to either the cell background or the cell text. } \details{ -The \code{col_*()} functions from the scales package can be used in the -\code{colors} argument. These functions map data values (\code{numeric} or -\code{factor}/\code{character}) to colors according to the provided palette. +The \code{col_*()} functions from the scales package can be used in the \code{colors} +argument. These functions map data values (\code{numeric} or \code{factor}/\code{character}) +to colors according to the provided palette. \itemize{ -\item \code{\link[scales]{col_numeric}()}: provides a simple linear mapping +\item \code{\link[scales:col_numeric]{scales::col_numeric()}}: provides a simple linear mapping from continuous numeric data to an interpolated palette. -\item \code{\link[scales]{col_bin}()}: provides a mapping of continuous +\item \code{\link[scales:col_bin]{scales::col_bin()}}: provides a mapping of continuous numeric data to value-based bins. This internally uses the -\code{\link[base]{cut}()} function. -\item \code{\link[scales]{col_quantile}()}: provides a mapping of continuous +\code{\link[base:cut]{base::cut()}} function. +\item \code{\link[scales:col_quantile]{scales::col_quantile()}}: provides a mapping of continuous numeric data to quantiles. This internally uses the -\code{\link[stats]{quantile}()} function. -\item \code{\link[scales]{col_factor}()}: provides a mapping of factors to +\code{\link[stats:quantile]{stats::quantile()}} function. +\item \code{\link[scales:col_factor]{scales::col_factor()}}: provides a mapping of factors to colors. If the palette is discrete and has a different number of colors than the number of factors, interpolation is used. } @@ -79,11 +78,11 @@ Choosing the right color palette can often be difficult because it's both hard to discover suitable palettes and then obtain the vector of colors. To make this process easier we can elect to use the \pkg{paletteer} package, which makes a wide range of palettes from various R packages readily -available. The \code{\link{info_paletteer}()} information table allows us to -easily inspect all of the discrete color palettes available in -\pkg{paletteer}. We only then need to specify the \code{package} and -\code{palette} when calling the \code{paletteer::paletteer_d()} function, -and, we get the palette as a vector of hexadecimal colors. +available. The \code{\link[=info_paletteer]{info_paletteer()}} information table allows us to easily +inspect all of the discrete color palettes available in \pkg{paletteer}. We +only then need to specify the \code{package} and \code{palette} when calling the +\code{paletteer::paletteer_d()} function, and, we get the palette as a vector of +hexadecimal colors. } \section{Figures}{ diff --git a/man/exibble.Rd b/man/exibble.Rd index ba8624e04b..787483cfbb 100644 --- a/man/exibble.Rd +++ b/man/exibble.Rd @@ -6,19 +6,19 @@ \title{A toy example tibble for testing with gt: exibble} \format{A tibble with 8 rows and 9 variables: \describe{ - \item{num}{a numeric column ordered with increasingly larger values} - \item{char}{a character column composed of names of fruits from \code{a} to - \code{h}} - \item{fctr}{a factor column with numbers from 1 to 8, written out} - \item{date, time, datetime}{character columns with dates, times, and - datetimes} - \item{currency}{a numeric column that is useful for testing currency-based - formatting} - \item{row}{a character column in the format \code{row_X} which can be - useful for testing with row captions in a table stub} - \item{group}{a character column with four \code{grp_a} values and four - \code{grp_b} values which can be useful for testing tables that contain - row groups} +\item{num}{a numeric column ordered with increasingly larger values} +\item{char}{a character column composed of names of fruits from \code{a} to +\code{h}} +\item{fctr}{a factor column with numbers from 1 to 8, written out} +\item{date, time, datetime}{character columns with dates, times, and +datetimes} +\item{currency}{a numeric column that is useful for testing currency-based +formatting} +\item{row}{a character column in the format \code{row_X} which can be +useful for testing with row captions in a table stub} +\item{group}{a character column with four \code{grp_a} values and four +\code{grp_b} values which can be useful for testing tables that contain +row groups} }} \usage{ exibble @@ -27,12 +27,11 @@ exibble This tibble contains data of a few different classes, which makes it well-suited for quick experimentation with the functions in this package. It contains only eight rows with numeric, character, and factor columns. The -last 4 rows contain \code{NA} values in the majority of this tibble's columns -(1 missing value per column). The \code{date}, \code{time}, and -\code{datetime} columns are character-based dates/times in the familiar ISO -8601 format. The \code{row} and \code{group} columns provide for unique -rownames and two groups (\code{grp_a} and \code{grp_b}) for experimenting -with the \code{\link{gt}()} function's \code{rowname_col} and +last 4 rows contain \code{NA} values in the majority of this tibble's columns (1 +missing value per column). The \code{date}, \code{time}, and \code{datetime} columns are +character-based dates/times in the familiar ISO 8601 format. The \code{row} and +\code{group} columns provide for unique rownames and two groups (\code{grp_a} and +\code{grp_b}) for experimenting with the \code{\link[=gt]{gt()}} function's \code{rowname_col} and \code{groupname_col} arguments. } \examples{ diff --git a/man/extract_summary.Rd b/man/extract_summary.Rd index b361f15dea..cd9924dc3f 100644 --- a/man/extract_summary.Rd +++ b/man/extract_summary.Rd @@ -7,7 +7,7 @@ extract_summary(data) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} +\item{data}{a table object that is created using the \code{\link[=gt]{gt()}} function.} } \value{ @@ -15,7 +15,7 @@ a list of data frames containing summary data. } \description{ Get a list of summary row data frames from a \code{gt_tbl} object where -summary rows were added via the \code{\link{summary_rows}()} function. The +summary rows were added via the \code{\link[=summary_rows]{summary_rows()}} function. The output data frames contain the \code{groupname} and \code{rowname} columns, whereby \code{rowname} contains descriptive stub labels for the summary rows. } diff --git a/man/fmt.Rd b/man/fmt.Rd index 7b3fc6fe21..8b6728135f 100644 --- a/man/fmt.Rd +++ b/man/fmt.Rd @@ -7,24 +7,20 @@ fmt(data, columns = NULL, rows = NULL, fns) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{fns}{Either a single formatting function or a named list of functions.} } @@ -32,32 +28,30 @@ to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} An object of class \code{gt_tbl}. } \description{ -The \code{fmt()} function provides greater control in formatting raw data -values than any of the specialized \code{fmt_*()} functions that are -available in \pkg{gt}. Along with the \code{columns} and \code{rows} -arguments that provide some precision in targeting data cells, the \code{fns} -argument allows you to define one or more functions for manipulating the raw -data. +The \code{fmt()} function provides greater control in formatting raw data values +than any of the specialized \code{fmt_*()} functions that are available in +\pkg{gt}. Along with the \code{columns} and \code{rows} arguments that provide some +precision in targeting data cells, the \code{fns} argument allows you to define +one or more functions for manipulating the raw data. } \details{ -If providing a single function to \code{fns}, the recommended format is in -the form: \code{fns = function(x) ...}. This single function will format the -targeted data cells the same way regardless of the output format (e.g., HTML, -LaTeX, RTF). +If providing a single function to \code{fns}, the recommended format is in the +form: \code{fns = function(x) ...}. This single function will format the targeted +data cells the same way regardless of the output format (e.g., HTML, LaTeX, +RTF). -If you require formatting of \code{x} that depends on the output format, a -list of functions can be provided for the \code{html}, \code{latex}, and -\code{default} contexts. This can be in the form of \code{fns = list(html = -function(x) ..., latex = function(x) ..., default = function(x) ...)}. In -this multiple-function case, we recommended including the \code{default} -function as a fallback if all contexts aren't provided. +If you require formatting of \code{x} that depends on the output format, a list of +functions can be provided for the \code{html}, \code{latex}, and \code{default} contexts. +This can be in the form of \code{fns = list(html = function(x) ..., latex = function(x) ..., default = function(x) ...)}. In this multiple-function case, +we recommended including the \code{default} function as a fallback if all contexts +aren't provided. -As with all of the \code{fmt_*()} functions, targeting of values is done -through \code{columns} and additionally by \code{rows} (if nothing is -provided for \code{rows} then entire columns are selected). A number of -helper functions exist to make targeting more effective. Conditional -formatting is possible by providing a conditional expression to the -\code{rows} argument. See the Arguments section for more information on this. +As with all of the \code{fmt_*()} functions, targeting of values is done through +\code{columns} and additionally by \code{rows} (if nothing is provided for \code{rows} then +entire columns are selected). A number of helper functions exist to make +targeting more effective. Conditional formatting is possible by providing a +conditional expression to the \code{rows} argument. See the Arguments section for +more information on this. } \section{Figures}{ diff --git a/man/fmt_currency.Rd b/man/fmt_currency.Rd index e828856699..e31e8f78be 100644 --- a/man/fmt_currency.Rd +++ b/man/fmt_currency.Rd @@ -11,43 +11,37 @@ fmt_currency(data, columns, rows = NULL, currency = "USD", placement = "left", incl_space = FALSE, locale = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{currency}{The currency to use for the numeric value. This input can be supplied as a 3-letter currency code (e.g., \code{"USD"} for U.S. Dollars, -\code{"EUR"} for the Euro currency). Use \code{\link{info_currencies}()} to -get an information table with all of the valid currency codes and examples -of each. Alternatively, we can provide a common currency name (e.g., -\code{"dollar"}, \code{"pound"}, \code{"yen"}, etc.) to simplify the -process. Use \code{\link{info_currencies}()} with the \code{type == -"symbol"} option to view an information table with all of the supported -currency symbol names along with examples. If nothing is provided then -\code{"USD"} will be used.} +\code{"EUR"} for the Euro currency). Use \code{\link[=info_currencies]{info_currencies()}} to get an +information table with all of the valid currency codes and examples of +each. Alternatively, we can provide a common currency name (e.g., +\code{"dollar"}, \code{"pound"}, \code{"yen"}, etc.) to simplify the process. Use +\code{\link[=info_currencies]{info_currencies()}} with the \code{type == "symbol"} option to view an +information table with all of the supported currency symbol names along +with examples. If nothing is provided then \code{"USD"} will be used.} \item{use_subunits}{An option for whether the subunits portion of a currency value should be displayed.} \item{accounting}{An option to use accounting style for currency values. With -\code{FALSE} (the default), negative values will be shown with a negative -sign. Using \code{accounting = TRUE} will put negative values in -parentheses.} +\code{FALSE} (the default), negative values will be shown with a minus sign. +Using \code{accounting = TRUE} will put negative values in parentheses.} \item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} @@ -56,38 +50,35 @@ use. The default number of decimal places is \code{2}.} group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} -\item{scale_by}{A value to scale the input. The default is \code{1.0}. All -numeric values will be multiplied by this value first before undergoing -formatting. This value will be ignored if using any of the \code{suffixing} -options (i.e., where \code{suffixing} is not set to \code{FALSE}).} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All numeric +values will be multiplied by this value first before undergoing formatting. +This value will be ignored if using any of the \code{suffixing} options (i.e., +where \code{suffixing} is not set to \code{FALSE}).} \item{suffixing}{An option to scale and apply suffixes to larger numbers -(e.g., \code{1924000} can be transformed to \code{1.92M}). This option can -accept a logical value, where \code{FALSE} (the default) will not perform -this transformation and \code{TRUE} will apply thousands (\code{K}), -millions (\code{M}), billions (\code{B}), and trillions (\code{T}) suffixes -after automatic value scaling. We can also specify which symbols to use for -each of the value ranges by using a character vector of the preferred -symbols to replace the defaults (e.g., \code{c("k", "Ml", "Bn", "Tr")}). -Including \code{NA} values in the vector will ensure that the particular -range will either not be included in the transformation (e.g, \code{c(NA, -"M", "B", "T")} won't modify numbers in the thousands range) or the range -will inherit a previous suffix (e.g., with \code{c("K", "M", NA, "T")}, all -numbers in the range of millions and billions will be in terms of -millions). Any use of \code{suffixing} (where not \code{FALSE}) means that -any value provided to \code{scale_by} will be ignored.} +(e.g., \code{1924000} can be transformed to \code{1.92M}). This option can accept a +logical value, where \code{FALSE} (the default) will not perform this +transformation and \code{TRUE} will apply thousands (\code{K}), millions (\code{M}), +billions (\code{B}), and trillions (\code{T}) suffixes after automatic value scaling. +We can also specify which symbols to use for each of the value ranges by +using a character vector of the preferred symbols to replace the defaults +(e.g., \code{c("k", "Ml", "Bn", "Tr")}). Including \code{NA} values in the vector +will ensure that the particular range will either not be included in the +transformation (e.g, \code{c(NA, "M", "B", "T")} won't modify numbers in the +thousands range) or the range will inherit a previous suffix (e.g., with +\code{c("K", "M", NA, "T")}, all numbers in the range of millions and billions +will be in terms of millions). Any use of \code{suffixing} (where not \code{FALSE}) +means that any value provided to \code{scale_by} will be ignored.} \item{pattern}{A formatting pattern that allows for decoration of the -formatted value. The value itself is represented by \code{{x}} and all -other characters are taken to be string literals.} +formatted value. The value itself is represented by \code{{x}} and all other +characters are taken to be string literals.} \item{sep_mark}{The mark to use as a separator between groups of digits -(e.g., using \code{sep_mark = ","} with \code{1000} would result in a -formatted value of \code{1,000}).} +(e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value +of \code{1,000}).} -\item{dec_mark}{The character to use as a decimal mark (e.g., using -\code{dec_mark = ","} with \code{0.152} would result in a formatted value -of \code{0,152}).} +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} \item{placement}{The placement of the currency symbol. This can be either be \code{left} (the default) or \code{right}.} @@ -98,9 +89,9 @@ and the currency symbol. The default is to not introduce a space character.} \item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid -locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a -useful reference for all of the locales that are supported.} +locale ID will override any values provided in \code{sep_mark} and \code{dec_mark}. +We can use the \code{\link[=info_locales]{info_locales()}} function as a useful reference for all of +the locales that are supported.} } \value{ An object of class \code{gt_tbl}. @@ -133,15 +124,14 @@ currency formatting specific to the chosen locale } } \details{ -We can use the \code{\link{info_currencies}()} function for a useful -reference on all of the possible inputs to \code{currency}. - -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +We can use the \code{\link[=info_currencies]{info_currencies()}} function for a useful reference on all of +the possible inputs to the \code{currency} argument. + +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_date.Rd b/man/fmt_date.Rd index 413237405a..f958c035db 100644 --- a/man/fmt_date.Rd +++ b/man/fmt_date.Rd @@ -7,29 +7,24 @@ fmt_date(data, columns, rows = NULL, date_style = 2) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} -\item{date_style}{The date style to use. Supply a number (from \code{1} to -\code{14}) that corresponds to the preferred date style. Use -\code{\link{info_date_style}()} to see the different numbered and named date -presets.} +\item{date_style}{The date style to use. Supply a number (from \code{1} to \code{14}) +that corresponds to the preferred date style. Use \code{\link[=info_date_style]{info_date_style()}} to +see the different numbered and named date presets.} } \value{ An object of class \code{gt_tbl}. @@ -37,10 +32,9 @@ An object of class \code{gt_tbl}. \description{ Format input date values that are either of the \code{Date} type, or, are character-based and expressed according to the ISO 8601 date format -(\code{YYYY-MM-DD}). Once the appropriate data cells are targeted with -\code{columns} (and, optionally, \code{rows}), we can simply apply a preset -date style (see table in \code{\link{info_date_style}()} for info) to format -the dates. +(\code{YYYY-MM-DD}). Once the appropriate data cells are targeted with \code{columns} +(and, optionally, \code{rows}), we can simply apply a preset date style (see table +in \code{\link[=info_date_style]{info_date_style()}} for info) to format the dates. } \details{ The following date styles are available for simpler formatting of ISO dates @@ -63,15 +57,14 @@ The following date styles are available for simpler formatting of ISO dates \item y.mn.day: \code{0/02/29} } -We can use the \code{\link{info_date_style}()} function for a useful -reference on all of the possible inputs to \code{date_style}. +We can use the \code{\link[=info_date_style]{info_date_style()}} function for a useful reference on all of +the possible inputs to \code{date_style}. -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_datetime.Rd b/man/fmt_datetime.Rd index b778472de9..6fded89bcf 100644 --- a/man/fmt_datetime.Rd +++ b/man/fmt_datetime.Rd @@ -8,45 +8,39 @@ fmt_datetime(data, columns, rows = NULL, date_style = 2, time_style = 2) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} -\item{date_style}{The date style to use. Supply a number (from \code{1} to -\code{14}) that corresponds to the preferred date style. Use -\code{\link{info_date_style}()} to see the different numbered and named date -presets.} +\item{date_style}{The date style to use. Supply a number (from \code{1} to \code{14}) +that corresponds to the preferred date style. Use \code{\link[=info_date_style]{info_date_style()}} to +see the different numbered and named date presets.} -\item{time_style}{The time style to use. Supply a number (from \code{1} to -\code{5}) that corresponds to the preferred time style. Use -\code{\link{info_time_style}()} to see the different numbered and named time -presets.} +\item{time_style}{The time style to use. Supply a number (from \code{1} to \code{5}) +that corresponds to the preferred time style. Use \code{\link[=info_time_style]{info_time_style()}} to +see the different numbered and named time presets.} } \value{ An object of class \code{gt_tbl}. } \description{ Format input date-time values that are character-based and expressed -according to the ISO 8601 date-time format (\code{YYYY-MM-DD HH:MM:SS}). Once -the appropriate data cells are targeted with \code{columns} (and, optionally, -\code{rows}), we can simply apply preset date and time styles (see tables in -\code{\link{info_date_style}()} and \code{\link{info_time_style}()} for more -info) to format the data-time values. +according to the ISO 8601 date-time format (\code{YYYY-MM-DD HH:MM:SS}). Once the +appropriate data cells are targeted with \code{columns} (and, optionally, \code{rows}), +we can simply apply preset date and time styles (see tables in +\code{\link[=info_date_style]{info_date_style()}} and \code{\link[=info_time_style]{info_time_style()}} for more info) to format the +data-time values. } \details{ The following date styles are available for simpler formatting of the date @@ -71,8 +65,7 @@ dates): } The following time styles are available for simpler formatting of the time -portion (all using the input time of \code{14:35:00} in the example output -times): +portion (all using the input time of \code{14:35:00} in the example output times): \enumerate{ \item hms: \code{14:35:00} @@ -82,16 +75,15 @@ times): \item h_p: \code{2 PM} } -We can use the \code{\link{info_date_style}()} and -\code{\link{info_time_style}()} functions as useful references for all of the -possible inputs to \code{date_style} and \code{time_style}. +We can use the \code{\link[=info_date_style]{info_date_style()}} and \code{\link[=info_time_style]{info_time_style()}} functions as +useful references for all of the possible inputs to \code{date_style} and +\code{time_style}. -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_markdown.Rd b/man/fmt_markdown.Rd index c5b6e6acbb..c989f8cc49 100644 --- a/man/fmt_markdown.Rd +++ b/man/fmt_markdown.Rd @@ -7,24 +7,20 @@ fmt_markdown(data, columns, rows = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} } \value{ An object of class \code{gt_tbl}. @@ -34,12 +30,11 @@ Any Markdown-formatted text in the incoming cells will be transformed to the appropriate output type during render when using \code{fmt_markdown()}. } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_missing.Rd b/man/fmt_missing.Rd index ad231fcdd7..35ec6a1d9e 100644 --- a/man/fmt_missing.Rd +++ b/man/fmt_missing.Rd @@ -7,24 +7,20 @@ fmt_missing(data, columns, rows = NULL, missing_text = "---") } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{missing_text}{The text to be used in place of \code{NA} values in the rendered table.} @@ -33,18 +29,17 @@ rendered table.} An object of class \code{gt_tbl}. } \description{ -Wherever there is missing data (i.e., \code{NA} values) a customizable mark -may present better than the standard \code{NA} text that would otherwise -appear. The \code{fmt_missing()} function allows for this replacement through -its \code{missing_text} argument (where an em dash serves as the default). +Wherever there is missing data (i.e., \code{NA} values) a customizable mark may +present better than the standard \code{NA} text that would otherwise appear. The +\code{fmt_missing()} function allows for this replacement through its +\code{missing_text} argument (where an em dash serves as the default). } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_number.Rd b/man/fmt_number.Rd index da2129b4fe..86123e2ec6 100644 --- a/man/fmt_number.Rd +++ b/man/fmt_number.Rd @@ -10,24 +10,20 @@ fmt_number(data, columns, rows = NULL, decimals = 2, dec_mark = ".", locale = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} @@ -39,45 +35,42 @@ trailing zeros (those redundant zeros after the decimal mark).} group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} -\item{scale_by}{A value to scale the input. The default is \code{1.0}. All -numeric values will be multiplied by this value first before undergoing -formatting. This value will be ignored if using any of the \code{suffixing} -options (i.e., where \code{suffixing} is not set to \code{FALSE}).} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All numeric +values will be multiplied by this value first before undergoing formatting. +This value will be ignored if using any of the \code{suffixing} options (i.e., +where \code{suffixing} is not set to \code{FALSE}).} \item{suffixing}{An option to scale and apply suffixes to larger numbers -(e.g., \code{1924000} can be transformed to \code{1.92M}). This option can -accept a logical value, where \code{FALSE} (the default) will not perform -this transformation and \code{TRUE} will apply thousands (\code{K}), -millions (\code{M}), billions (\code{B}), and trillions (\code{T}) suffixes -after automatic value scaling. We can also specify which symbols to use for -each of the value ranges by using a character vector of the preferred -symbols to replace the defaults (e.g., \code{c("k", "Ml", "Bn", "Tr")}). -Including \code{NA} values in the vector will ensure that the particular -range will either not be included in the transformation (e.g, \code{c(NA, -"M", "B", "T")} won't modify numbers in the thousands range) or the range -will inherit a previous suffix (e.g., with \code{c("K", "M", NA, "T")}, all -numbers in the range of millions and billions will be in terms of -millions). Any use of \code{suffixing} (where not \code{FALSE}) means that -any value provided to \code{scale_by} will be ignored.} +(e.g., \code{1924000} can be transformed to \code{1.92M}). This option can accept a +logical value, where \code{FALSE} (the default) will not perform this +transformation and \code{TRUE} will apply thousands (\code{K}), millions (\code{M}), +billions (\code{B}), and trillions (\code{T}) suffixes after automatic value scaling. +We can also specify which symbols to use for each of the value ranges by +using a character vector of the preferred symbols to replace the defaults +(e.g., \code{c("k", "Ml", "Bn", "Tr")}). Including \code{NA} values in the vector +will ensure that the particular range will either not be included in the +transformation (e.g, \code{c(NA, "M", "B", "T")} won't modify numbers in the +thousands range) or the range will inherit a previous suffix (e.g., with +\code{c("K", "M", NA, "T")}, all numbers in the range of millions and billions +will be in terms of millions). Any use of \code{suffixing} (where not \code{FALSE}) +means that any value provided to \code{scale_by} will be ignored.} \item{pattern}{A formatting pattern that allows for decoration of the -formatted value. The value itself is represented by \code{{x}} and all -other characters are taken to be string literals.} +formatted value. The value itself is represented by \code{{x}} and all other +characters are taken to be string literals.} \item{sep_mark}{The mark to use as a separator between groups of digits -(e.g., using \code{sep_mark = ","} with \code{1000} would result in a -formatted value of \code{1,000}).} +(e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value +of \code{1,000}).} -\item{dec_mark}{The character to use as a decimal mark (e.g., using -\code{dec_mark = ","} with \code{0.152} would result in a formatted value -of \code{0,152}).} +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} \item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid -locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a -useful reference for all of the locales that are supported.} +locale ID will override any values provided in \code{sep_mark} and \code{dec_mark}. +We can use the \code{\link[=info_locales]{info_locales()}} function as a useful reference for all of +the locales that are supported.} } \value{ An object of class \code{gt_tbl}. @@ -102,12 +95,11 @@ formatting specific to the chosen locale } } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_passthrough.Rd b/man/fmt_passthrough.Rd index 889865bd27..e9b33ab630 100644 --- a/man/fmt_passthrough.Rd +++ b/man/fmt_passthrough.Rd @@ -8,56 +8,49 @@ fmt_passthrough(data, columns, rows = NULL, escape = TRUE, pattern = "{x}") } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{escape}{An option to escape text according to the final output format of the table. For example, if a LaTeX table is to be generated then LaTeX escaping would be performed during rendering. By default this is set to -\code{TRUE} and setting to \code{FALSE} is useful in the case where -LaTeX-formatted text should be passed through to the output LaTeX table -unchanged.} +\code{TRUE} and setting to \code{FALSE} is useful in the case where LaTeX-formatted +text should be passed through to the output LaTeX table unchanged.} \item{pattern}{A formatting pattern that allows for decoration of the -formatted value. The value itself is represented by \code{{x}} and all -other characters are taken to be string literals.} +formatted value. The value itself is represented by \code{{x}} and all other +characters are taken to be string literals.} } \value{ An object of class \code{gt_tbl}. } \description{ Format by passing data through no other transformation other than: (1) -coercing to \code{character} (as all the \code{fmt_*()} functions do), and -(2) applying prefixed or suffixed text via the \code{pattern} argument (the -default is to apply nothing). All of this is useful when don't want to modify -the input data other than to decorate it within a pattern. Also, this -function is useful when used as a \code{formatter} function in the -\code{summary_rows} function, where the output may be text or useful as is -(that function requires a formatter function). +coercing to \code{character} (as all the \code{fmt_*()} functions do), and (2) applying +text via the \code{pattern} argument (the default is to apply nothing). All of +this is useful when don't want to modify the input data other than to +decorate it within a pattern. Also, this function is useful when used as the +\code{formatter} function in the \code{\link[=summary_rows]{summary_rows()}} function, where the output may +be text or useful as is. } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_percent.Rd b/man/fmt_percent.Rd index 8a99e6969d..8120398ba5 100644 --- a/man/fmt_percent.Rd +++ b/man/fmt_percent.Rd @@ -10,24 +10,20 @@ fmt_percent(data, columns, rows = NULL, decimals = 2, placement = "right", locale = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} @@ -40,16 +36,14 @@ group separator is set by \code{sep_mark} and overridden if a locale ID is provided to \code{locale}. This setting is \code{TRUE} by default.} \item{pattern}{A formatting pattern that allows for decoration of the -formatted value. The value itself is represented by \code{{x}} and all -other characters are taken to be string literals.} +formatted value. The value itself is represented by \code{{x}} and all other +characters are taken to be string literals.} \item{sep_mark}{The mark to use as a separator between groups of digits -(e.g., using \code{sep_mark = ","} with \code{1000} would result in a -formatted value of \code{1,000}).} +(e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value +of \code{1,000}).} -\item{dec_mark}{The character to use as a decimal mark (e.g., using -\code{dec_mark = ","} with \code{0.152} would result in a formatted value -of \code{0,152}).} +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} \item{incl_space}{An option for whether to include a space between the value and the percent sign. The default is to not introduce a space character.} @@ -60,9 +54,9 @@ and the percent sign. The default is to not introduce a space character.} \item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid -locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a -useful reference for all of the locales that are supported.} +locale ID will override any values provided in \code{sep_mark} and \code{dec_mark}. +We can use the \code{\link[=info_locales]{info_locales()}} function as a useful reference for all of +the locales that are supported.} } \value{ an object of class \code{gt_tbl}. @@ -70,9 +64,9 @@ an object of class \code{gt_tbl}. \description{ With numeric values in a \pkg{gt} table, we can perform percentage-based formatting. It is assumed the input numeric values are in a fractional format -since the numbers will be automatically multiplied by \code{100} before -decorating with a percent sign. For more control over percentage formatting, -we can use the following options: +since the numbers will be automatically multiplied by \code{100} before decorating +with a percent sign. For more control over percentage formatting, we can use +the following options: \itemize{ \item percent sign placement: the percent sign can be placed after or before the values and a space can be inserted between the symbol and the @@ -88,12 +82,11 @@ formatting specific to the chosen locale } } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_scientific.Rd b/man/fmt_scientific.Rd index 28d7aa20f1..2a49fcf0f5 100644 --- a/man/fmt_scientific.Rd +++ b/man/fmt_scientific.Rd @@ -9,24 +9,20 @@ fmt_scientific(data, columns, rows = NULL, decimals = 2, sep_mark = ",", dec_mark = ".", locale = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} \item{decimals}{An option to specify the exact number of decimal places to use. The default number of decimal places is \code{2}.} @@ -34,29 +30,27 @@ use. The default number of decimal places is \code{2}.} \item{drop_trailing_zeros}{A logical value that allows for removal of trailing zeros (those redundant zeros after the decimal mark).} -\item{scale_by}{A value to scale the input. The default is \code{1.0}. All -numeric values will be multiplied by this value first before undergoing -formatting. This value will be ignored if using any of the \code{suffixing} -options (i.e., where \code{suffixing} is not set to \code{FALSE}).} +\item{scale_by}{A value to scale the input. The default is \code{1.0}. All numeric +values will be multiplied by this value first before undergoing formatting. +This value will be ignored if using any of the \code{suffixing} options (i.e., +where \code{suffixing} is not set to \code{FALSE}).} \item{pattern}{A formatting pattern that allows for decoration of the -formatted value. The value itself is represented by \code{{x}} and all -other characters are taken to be string literals.} +formatted value. The value itself is represented by \code{{x}} and all other +characters are taken to be string literals.} \item{sep_mark}{The mark to use as a separator between groups of digits -(e.g., using \code{sep_mark = ","} with \code{1000} would result in a -formatted value of \code{1,000}).} +(e.g., using \code{sep_mark = ","} with \code{1000} would result in a formatted value +of \code{1,000}).} -\item{dec_mark}{The character to use as a decimal mark (e.g., using -\code{dec_mark = ","} with \code{0.152} would result in a formatted value -of \code{0,152}).} +\item{dec_mark}{The character to use as a decimal mark (e.g., using \code{dec_mark = ","} with \code{0.152} would result in a formatted value of \code{0,152}).} \item{locale}{An optional locale ID that can be used for formatting the value according the locale's rules. Examples include \code{"en_US"} for English (United States) and \code{"fr_FR"} for French (France). The use of a valid -locale ID will override any values provided in \code{sep_mark} and -\code{dec_mark}. We can use the \code{\link{info_locales}()} function as a -useful reference for all of the locales that are supported.} +locale ID will override any values provided in \code{sep_mark} and \code{dec_mark}. +We can use the \code{\link[=info_locales]{info_locales()}} function as a useful reference for all of +the locales that are supported.} } \value{ An object of class \code{gt_tbl}. @@ -76,12 +70,11 @@ formatting specific to the chosen locale } } \details{ -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/fmt_time.Rd b/man/fmt_time.Rd index 7569b2af22..c647e53b2f 100644 --- a/man/fmt_time.Rd +++ b/man/fmt_time.Rd @@ -7,39 +7,34 @@ fmt_time(data, columns, rows = NULL, time_style = 2) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{columns}{The columns to format. Can either be a series of column names -provided in \code{vars()}, a vector of column indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +provided in \code{\link[=vars]{vars()}}, a vector of column indices, or a helper function +focused on selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}.} \item{rows}{Optional rows to format. Not providing any value results in all -rows in \code{columns} being formatted. Can either be a vector of row -captions provided \code{c()}, a vector of row indices, or a helper function -focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}. We can also use expressions to filter down -to the rows we need (e.g., \code{[colname_1] > 100 & [colname_2] < 50}).} +rows in \code{columns} being formatted. Can either be a vector of row captions +provided \code{\link[=c]{c()}}, a vector of row indices, or a helper function focused on +selections. The select helper functions are: \code{\link[=starts_with]{starts_with()}}, +\code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and \code{\link[=everything]{everything()}}. +We can also use expressions to filter down to the rows we need (e.g., +\code{[colname_1] > 100 & [colname_2] < 50}).} -\item{time_style}{The time style to use. Supply a number (from \code{1} to -\code{5}) that corresponds to the preferred time style. Use -\code{\link{info_time_style}()} to see the different numbered and named time -presets.} +\item{time_style}{The time style to use. Supply a number (from \code{1} to \code{5}) +that corresponds to the preferred time style. Use \code{\link[=info_time_style]{info_time_style()}} to +see the different numbered and named time presets.} } \value{ An object of class \code{gt_tbl}. } \description{ Format input time values that are character-based and expressed according to -the ISO 8601 time format (\code{HH:MM:SS}). Once the appropriate data cells -are targeted with \code{columns} (and, optionally, \code{rows}), we can -simply apply a preset time style (see table in -\code{\link{info_time_style}()} for info) to format the times. +the ISO 8601 time format (\code{HH:MM:SS}). Once the appropriate data cells are +targeted with \code{columns} (and, optionally, \code{rows}), we can simply apply a +preset time style (see table in \code{\link[=info_time_style]{info_time_style()}} for info) to format the +times. } \details{ The following time styles are available for simpler formatting of ISO times @@ -53,15 +48,14 @@ The following time styles are available for simpler formatting of ISO times \item h_p: \code{2 PM} } -We can use the \code{\link{info_time_style}()} function for a useful -reference on all of the possible inputs to \code{time_style}. +We can use the \code{\link[=info_time_style]{info_time_style()}} function for a useful reference on all of +the possible inputs to \code{time_style}. -Targeting of values is done through \code{columns} and additionally by -\code{rows} (if nothing is provided for \code{rows} then entire columns are -selected). A number of helper functions exist to make targeting more -effective. Conditional formatting is possible by providing a conditional -expression to the \code{rows} argument. See the Arguments section for more -information on this. +Targeting of values is done through \code{columns} and additionally by \code{rows} (if +nothing is provided for \code{rows} then entire columns are selected). A number of +helper functions exist to make targeting more effective. Conditional +formatting is possible by providing a conditional expression to the \code{rows} +argument. See the Arguments section for more information on this. } \section{Figures}{ diff --git a/man/ggplot_image.Rd b/man/ggplot_image.Rd index 616c8dfe6e..1b2953b90d 100644 --- a/man/ggplot_image.Rd +++ b/man/ggplot_image.Rd @@ -7,32 +7,31 @@ ggplot_image(plot_object, height = 100, aspect_ratio = 1) } \arguments{ -\item{plot_object}{a ggplot plot object.} +\item{plot_object}{A ggplot plot object.} -\item{height}{the absolute height (px) of the image in the table cell.} +\item{height}{The absolute height (px) of the image in the table cell.} -\item{aspect_ratio}{the plot's final aspect ratio. Where the height of the +\item{aspect_ratio}{The plot's final aspect ratio. Where the height of the plot is fixed using the \code{height} argument, the \code{aspect_ratio} will either compress (\code{aspect_ratio} < \code{1.0}) or expand (\code{aspect_ratio} > \code{1.0}) the plot horizontally. The default value of \code{1.0} will neither compress nor expand the plot.} } \value{ -a character object with an HTML fragment that can be placed inside of - a cell. +A character object with an HTML fragment that can be placed inside of +a cell. } \description{ We can add a \pkg{ggplot2} plot inside of a table with the help of the -\code{ggplot_image()} function. The function provides a convenient way to -generate an HTML fragment with a \code{ggplot} object. Because this function -is currently HTML-based, it is only useful for HTML table output. To use this -function inside of data cells, it is recommended that the -\code{\link{text_transform}()} function is used. With that function, we can -specify which data cells to target and then include a call to -\code{ggplot_image()} within the required user-defined function (for the -\code{fn} argument). If we want to include a plot in other places (e.g., in -the header, within footnote text, etc.) we need to use \code{ggplot_image()} -within the \code{\link{html}()} helper function. +\code{ggplot_image()} function. The function provides a convenient way to generate +an HTML fragment with a \code{ggplot} object. Because this function is currently +HTML-based, it is only useful for HTML table output. To use this function +inside of data cells, it is recommended that the \code{\link[=text_transform]{text_transform()}} function +is used. With that function, we can specify which data cells to target and +then include a call to \code{ggplot_image()} within the required user-defined +function (for the \code{fn} argument). If we want to include a plot in other +places (e.g., in the header, within footnote text, etc.) we need to use +\code{ggplot_image()} within the \code{\link[=html]{html()}} helper function. } \details{ By itself, the function creates an HTML image tag with an image URI embedded @@ -42,11 +41,10 @@ evaluates to: \code{ src= style=\"height:100px;\">} -where a height of \code{100px} is a default height chosen to work well within -the heights of most table rows. There is the option to modify the aspect -ratio of the plot (the default \code{aspect_ratio} is \code{1.0}) and this is -useful for elongating any given plot to fit better within the table -construct. +where a height of \code{100px} is a default height chosen to work well within the +heights of most table rows. There is the option to modify the aspect ratio of +the plot (the default \code{aspect_ratio} is \code{1.0}) and this is useful for +elongating any given plot to fit better within the table construct. } \section{Figures}{ diff --git a/man/gt-options.Rd b/man/gt-options.Rd index 88265c3872..b40a1492ad 100644 --- a/man/gt-options.Rd +++ b/man/gt-options.Rd @@ -9,11 +9,11 @@ \section{Package options}{ -\pkg{gt} uses the following \code{\link{options}} to configure behavior: +\pkg{gt} uses the following \code{\link[=options]{options()}} to configure behavior: \itemize{ - \item \code{gt.stub_group.sep}: a separator between groups for the - stub group label. +\item \code{gt.stub_group.sep}: a separator between groups for the +stub group label. } } diff --git a/man/gt.Rd b/man/gt.Rd index 00a220568b..2c2fe9b9eb 100644 --- a/man/gt.Rd +++ b/man/gt.Rd @@ -9,46 +9,45 @@ gt(data, rowname_col = "rowname", groupname_col = "groupname", stub_group.sep = getOption("gt.stub_group.sep", " - ")) } \arguments{ -\item{data}{a \code{data.frame} object or a tibble.} +\item{data}{A \code{data.frame} object or a tibble.} -\item{rowname_col}{the column name in the input \code{data} table to use as -row captions to be placed in the display table stub.} +\item{rowname_col}{The column name in the input \code{data} table to use as row +captions to be placed in the display table stub.} -\item{groupname_col}{the column name in the input \code{data} table to use as +\item{groupname_col}{The column name in the input \code{data} table to use as group labels for generation of stub row groups.} -\item{rownames_to_stub}{an option to take rownames from the input \code{data} +\item{rownames_to_stub}{An option to take rownames from the input \code{data} table as row captions in the display table stub.} -\item{stub_group.sep}{the separator to use between consecutive group names (a -possibility when providing \code{data} as a \code{grouped_df} with multiple -groups) in the displayed stub row group label.} +\item{stub_group.sep}{The separator to use between consecutive group names (a +possibility when providing \code{data} as a \code{grouped_df} with multiple groups) +in the displayed stub row group label.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ -The \code{gt()} function creates a \pkg{gt} table object when provided with -table data. Using this function is the first step in a typical \pkg{gt} -workflow. Once we have the \pkg{gt} table object, we can perform styling +The \code{gt()} function creates a \pkg{gt} table object when provided with table +data. Using this function is the first step in a typical \pkg{gt} workflow. +Once we have the \pkg{gt} table object, we can perform styling transformations before rendering to a display table of various formats (e.g., HTML, LaTeX, RTF). } \details{ There are a few data ingest options we can consider at this stage. We can -choose to create a table stub with rowname captions using the -\code{rowname_col} argument. Further to this, stub row groups can be created -with the \code{groupname_col}. Both arguments take the name of a column in -the input table data. Typically, the data in the \code{groupname_col} will -consist of categories of data in a table and the data in the -\code{rowname_col} are unique labels (perhaps unique across the entire table -or unique within groups). +choose to create a table stub with rowname captions using the \code{rowname_col} +argument. Further to this, stub row groups can be created with the +\code{groupname_col}. Both arguments take the name of a column in the input table +data. Typically, the data in the \code{groupname_col} will consist of categories +of data in a table and the data in the \code{rowname_col} are unique labels +(perhaps unique across the entire table or unique within groups). -Row groups can also be created by passing a \code{grouped_df} to \code{gt()} -by using the \code{dplyr::group_by()} function on the table data. In this -way, two or more columns of categorical data can be used to make row groups. -The \code{stub_group.sep} argument allows for control in how the row group -label will appear in the display table. +Row groups can also be created by passing a \code{grouped_df} to \code{gt()} by using +the \code{dplyr::group_by()} function on the table data. In this way, two or more +columns of categorical data can be used to make row groups. The +\code{stub_group.sep} argument allows for control in how the row group label will +appear in the display table. } \section{Figures}{ diff --git a/man/gt_output.Rd b/man/gt_output.Rd index aefa028b7e..da10b8a906 100644 --- a/man/gt_output.Rd +++ b/man/gt_output.Rd @@ -7,7 +7,7 @@ gt_output(outputId) } \arguments{ -\item{outputId}{an output variable from which to read the table.} +\item{outputId}{An output variable from which to read the table.} } \value{ A \pkg{gt} table output element that can be included in a panel. diff --git a/man/gt_preview.Rd b/man/gt_preview.Rd index 0053b14680..c648a20c17 100644 --- a/man/gt_preview.Rd +++ b/man/gt_preview.Rd @@ -7,38 +7,36 @@ gt_preview(data, top_n = 5, bottom_n = 1, incl_rownums = TRUE) } \arguments{ -\item{data}{a \code{data.frame} object or a tibble.} +\item{data}{A \code{data.frame} object or a tibble.} -\item{top_n}{this value will be used as the number of rows from the top of -the table to display. The default, \code{5}, will show the first five rows -of the table.} - -\item{bottom_n}{the value will be used as the number of rows from the bottom -of the table to display. The default, \code{1}, will show the final row of +\item{top_n}{This value will be used as the number of rows from the top of +the table to display. The default, \code{5}, will show the first five rows of the table.} -\item{incl_rownums}{an option to include the row numbers for \code{data} in -the table stub. By default, this is \code{TRUE}.} +\item{bottom_n}{The value will be used as the number of rows from the bottom +of the table to display. The default, \code{1}, will show the final row of the +table.} + +\item{incl_rownums}{An option to include the row numbers for \code{data} in the +table stub. By default, this is \code{TRUE}.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Sometimes you may want to see just a small portion of your input data. We can -use \code{gt_preview()} in place of \code{\link{gt}()} to get the first x -rows of data and the last y rows of data (which can be set by the -\code{top_n} and \code{bottom_n} arguments). It's not advised to use -additional \pkg{gt} API functions to further modify the output of -\code{gt_preview()}. Furthermore, you cannot pass a \pkg{gt} object to -\code{gt_preview()}. +use \code{gt_preview()} in place of \code{\link[=gt]{gt()}} to get the first x rows of data and the +last y rows of data (which can be set by the \code{top_n} and \code{bottom_n} +arguments). It's not advised to use additional \pkg{gt} API functions to +further modify the output of \code{gt_preview()}. Furthermore, you cannot pass a +\pkg{gt} object to \code{gt_preview()}. } \details{ -Any grouped data or magic columns such as \code{rowname} and \code{groupname} -will be ignored by \code{gt_preview()} and, as such, one cannot add a stub or -group rows in the output table. By default, the output table will include row -numbers in a stub (including a range of row numbers for the omitted rows). -This row numbering option can be deactivated by setting \code{incl_rownums} -to \code{FALSE}. +Any grouped data or magic columns such as \code{rowname} and \code{groupname} will be +ignored by \code{gt_preview()} and, as such, one cannot add a stub or group rows +in the output table. By default, the output table will include row numbers in +a stub (including a range of row numbers for the omitted rows). This row +numbering option can be deactivated by setting \code{incl_rownums} to \code{FALSE}. } \section{Figures}{ diff --git a/man/gtcars.Rd b/man/gtcars.Rd index f28b3a3fc0..d04bb2febb 100644 --- a/man/gtcars.Rd +++ b/man/gtcars.Rd @@ -6,24 +6,24 @@ \title{Deluxe automobiles from the 2014-2017 period} \format{A tibble with 47 rows and 15 variables: \describe{ - \item{mfr}{The name of the car manufacturer} - \item{model}{The car's model name} - \item{year}{The car's model year} - \item{trim}{A short description of the car model's trim} - \item{bdy_style}{An identifier of the car's body style, which is either - \code{coupe}, \code{convertible}, \code{sedan}, or \code{hatchback}} - \item{hp, hp_rpm}{The car's horsepower and the associated RPM level} - \item{trq, trq_rpm}{The car's torque and the associated RPM level} - \item{mpg_c, mpg_h}{The miles per gallon fuel efficiency rating for city - and highway driving} - \item{drivetrain}{The car's drivetrain which, for this dataset is either - \code{rwd} (Rear Wheel Drive) or \code{awd} (All Wheel Drive)} - \item{trsmn}{The codified transmission type, where the number part is - the number of gears; the car could have automatic transmission - (\code{a}), manual transmission (\code{m}), an option to switch between - both types (\code{am}), or, direct drive (\code{dd})} - \item{ctry_origin}{The country name for where the vehicle manufacturer - is headquartered} +\item{mfr}{The name of the car manufacturer} +\item{model}{The car's model name} +\item{year}{The car's model year} +\item{trim}{A short description of the car model's trim} +\item{bdy_style}{An identifier of the car's body style, which is either +\code{coupe}, \code{convertible}, \code{sedan}, or \code{hatchback}} +\item{hp, hp_rpm}{The car's horsepower and the associated RPM level} +\item{trq, trq_rpm}{The car's torque and the associated RPM level} +\item{mpg_c, mpg_h}{The miles per gallon fuel efficiency rating for city +and highway driving} +\item{drivetrain}{The car's drivetrain which, for this dataset is either +\code{rwd} (Rear Wheel Drive) or \code{awd} (All Wheel Drive)} +\item{trsmn}{The codified transmission type, where the number part is +the number of gears; the car could have automatic transmission +(\code{a}), manual transmission (\code{m}), an option to switch between +both types (\code{am}), or, direct drive (\code{dd})} +\item{ctry_origin}{The country name for where the vehicle manufacturer +is headquartered} }} \source{ Various pages within \url{https://www.edmunds.com}. @@ -32,20 +32,20 @@ Various pages within \url{https://www.edmunds.com}. gtcars } \description{ -Expensive and fast cars. Not your father's \code{mtcars}. Each row describes -a car of a certain make, model, year, and trim. Basic specifications such as +Expensive and fast cars. Not your father's \code{mtcars}. Each row describes a car +of a certain make, model, year, and trim. Basic specifications such as horsepower, torque, EPA MPG ratings, type of drivetrain, and transmission characteristics are provided. The country of origin for the car manufacturer is also given. } \details{ -All of the \code{gtcars} have something else in common (aside from the high -asking prices): they are all grand tourer vehicles. These are proper GT cars -that blend pure driving thrills with a level of comfort that is more expected -from a fine limousine (e.g., a Rolls-Royce Phantom EWB). You'll find that, -with these cars, comfort is emphasized over all-out performance. -Nevertheless, the driving experience should also mean motoring at speed, -doing so in style and safety. +All of the \code{gtcars} have something else in common (aside from the high asking +prices): they are all grand tourer vehicles. These are proper GT cars that +blend pure driving thrills with a level of comfort that is more expected from +a fine limousine (e.g., a Rolls-Royce Phantom EWB). You'll find that, with +these cars, comfort is emphasized over all-out performance. Nevertheless, the +driving experience should also mean motoring at speed, doing so in style and +safety. } \examples{ # Here is a glimpse at the data diff --git a/man/gtsave.Rd b/man/gtsave.Rd index 1ba00a7dca..588d69d9ad 100644 --- a/man/gtsave.Rd +++ b/man/gtsave.Rd @@ -7,31 +7,30 @@ gtsave(data, filename, ...) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{filename}{the file name to create on disk. Ensure that an extension -compatible with the output types is provided (\code{.html}, \code{.tex}, -\code{.ltx}, \code{.rtf}). If a custom save function is provided then the -file extension is disregarded.} +\item{filename}{The file name to create on disk. Ensure that an extension +compatible with the output types is provided (\code{.html}, \code{.tex}, \code{.ltx}, +\code{.rtf}). If a custom save function is provided then the file extension is +disregarded.} -\item{...}{all other options passed to the appropriate internal saving +\item{...}{All other options passed to the appropriate internal saving function.} } \description{ -The \code{gtsave()} function makes it easy to save a \pkg{gt} table to a -file. The function guesses the file type by the extension provided in the -output filename, producing either an HTML, LaTeX, or RTF file. +The \code{gtsave()} function makes it easy to save a \pkg{gt} table to a file. The +function guesses the file type by the extension provided in the output +filename, producing either an HTML, LaTeX, or RTF file. } \details{ -Output filenames with either the \code{.html} or \code{.htm} extensions will -produce an HTML document. In this case, we can pass a \code{TRUE} or -\code{FALSE} value to the \code{inline_css} option to obtain an HTML document -with inlined CSS styles (the default is \code{FALSE}). More details on CSS -inlining are available at \code{\link{as_raw_html}()}. +Output filenames with either the \code{.html} or \code{.htm} extensions will produce an +HTML document. In this case, we can pass a \code{TRUE} or \code{FALSE} value to the +\code{inline_css} option to obtain an HTML document with inlined CSS styles (the +default is \code{FALSE}). More details on CSS inlining are available at +\code{\link[=as_raw_html]{as_raw_html()}}. -If the output filename is either of \code{.tex}, \code{.ltx}, or \code{.rnw}, -a LaTeX document is produced. An output filename of \code{.rtf} will generate -an RTF document. The LaTeX and RTF saving function don't have any options to -pass to \code{...}. +If the output filename is either of \code{.tex}, \code{.ltx}, or \code{.rnw}, a LaTeX +document is produced. An output filename of \code{.rtf} will generate an RTF +document. The LaTeX and RTF saving function don't have any options to pass to +\code{...}. } diff --git a/man/html.Rd b/man/html.Rd index 8f0355116c..de978a5a55 100644 --- a/man/html.Rd +++ b/man/html.Rd @@ -7,12 +7,12 @@ html(text, ...) } \arguments{ -\item{text, ...}{the text that is understood to be HTML text, which is to be +\item{text, ...}{The text that is understood to be HTML text, which is to be preserved.} } \value{ -a character object that is tagged as an HTML fragment that is not to - be sanitized. +A character object that is tagged as an HTML fragment that is not to +be sanitized. a character object of class \code{html}. } diff --git a/man/info_currencies.Rd b/man/info_currencies.Rd index 7036cdc006..3f3ce2d313 100644 --- a/man/info_currencies.Rd +++ b/man/info_currencies.Rd @@ -7,24 +7,24 @@ info_currencies(type = c("code", "symbol"), begins_with = NULL) } \arguments{ -\item{type}{the type of currency information provided. Can either be -\code{code} where currency information corresponding to 3-letter currency -codes is provided, or \code{symbol} where currency info for common currency -names (e.g., dollar, pound, yen, etc.) is returned.} +\item{type}{The type of currency information provided. Can either be \code{code} +where currency information corresponding to 3-letter currency codes is +provided, or \code{symbol} where currency info for common currency names (e.g., +dollar, pound, yen, etc.) is returned.} -\item{begins_with}{providing a single letter will filter currencies to only +\item{begins_with}{Providing a single letter will filter currencies to only those that begin with that letter in their currency code. The default -(\code{NULL}) will produce a table with all currencies displayed. This -option only constrains the information table where \code{type == "code"}.} +(\code{NULL}) will produce a table with all currencies displayed. This option +only constrains the information table where \code{type == "code"}.} } \description{ -The \code{fmt_currency()} function lets us format numeric values as -currencies. The table generated by the \code{info_currencies()} function -provides a quick reference to all the available currencies. The currency -identifiers are provided (name, 3-letter currency code, and 3-digit currency -code) along with the each currency's exponent value (number of digits of the -currency subunits). A formatted example is provided (based on the value of -\code{49.95}) to demonstrate the default formatting of each currency. +The \code{fmt_currency()} function lets us format numeric values as currencies. +The table generated by the \code{info_currencies()} function provides a quick +reference to all the available currencies. The currency identifiers are +provided (name, 3-letter currency code, and 3-digit currency code) along with +the each currency's exponent value (number of digits of the currency +subunits). A formatted example is provided (based on the value of \code{49.95}) to +demonstrate the default formatting of each currency. } \details{ There are 172 currencies, which can lead to a verbose display table. To make diff --git a/man/info_date_style.Rd b/man/info_date_style.Rd index 3da4ea5322..d6397f7197 100644 --- a/man/info_date_style.Rd +++ b/man/info_date_style.Rd @@ -7,11 +7,11 @@ info_date_style() } \description{ -The \code{fmt_date()} function lets us format date-based values in a -convenient manner using preset styles. The table generated by the -\code{info_date_style()} function provides a quick reference to all 14 -styles, with associated number codes, the format names, and example outputs -using a fixed date (\code{2000-02-29}). +The \code{fmt_date()} function lets us format date-based values in a convenient +manner using preset styles. The table generated by the \code{info_date_style()} +function provides a quick reference to all 14 styles, with associated number +codes, the format names, and example outputs using a fixed date +(\code{2000-02-29}). } \section{Figures}{ diff --git a/man/info_locales.Rd b/man/info_locales.Rd index a76492f25f..31e88c9332 100644 --- a/man/info_locales.Rd +++ b/man/info_locales.Rd @@ -7,25 +7,24 @@ info_locales(begins_with = NULL) } \arguments{ -\item{begins_with}{providing a single letter will filter locales to only +\item{begins_with}{Providing a single letter will filter locales to only those that begin with that letter in their base locale ID. The default (\code{NULL}) will produce a table with all locales displayed.} } \description{ Many of the \code{fmt_*()} functions have a \code{locale} argument that makes -locale-based formatting easier. The table generated by the -\code{info_locales()} function provides a quick reference to all the -available locales. The locale identifiers are provided (base locale ID, -common display name) along with the each locale's group and decimal separator -marks. A formatted numeric example is provided (based on the value of -\code{11027}) to demonstrate the default formatting of each locale. +locale-based formatting easier. The table generated by the \code{info_locales()} +function provides a quick reference to all the available locales. The locale +identifiers are provided (base locale ID, common display name) along with the +each locale's group and decimal separator marks. A formatted numeric example +is provided (based on the value of \code{11027}) to demonstrate the default +formatting of each locale. } \details{ There are 712 locales, which means that a very long display table is provided by default. To trim down the output table size, we can provide an initial -letter corresponding to the base locale ID to \code{begins_with}. This will -filter locales in the info table to just the set beginning with the supplied -letter. +letter corresponding to the base locale ID to \code{begins_with}. This will filter +locales in the info table to just the set beginning with the supplied letter. } \examples{ # Get a table of info on all of diff --git a/man/info_paletteer.Rd b/man/info_paletteer.Rd index 3a79eef62a..5687dac3f2 100644 --- a/man/info_paletteer.Rd +++ b/man/info_paletteer.Rd @@ -7,20 +7,20 @@ info_paletteer(color_pkgs = NULL) } \arguments{ -\item{color_pkgs}{a vector of color packages that determines which sets of +\item{color_pkgs}{A vector of color packages that determines which sets of palettes should be displayed in the information table. If this is \code{NULL} (the default) then all of the discrete palettes from all of the color packages represented in \pkg{paletteer} will be displayed.} } \description{ -While the \code{\link{data_color}()} function allows us to flexibly color -data cells in our \pkg{gt} table, the harder part of this process is -discovering and choosing color palettes that are suitable for the table -output. We can make this process much easier in two ways: (1) by using the -\pkg{paletteer} package, which makes a wide range of palettes from various R -packages readily available, and (2) calling the \code{info_paletteer()} -function to give us an information table that serves as a quick reference for -all of the discrete color palettes available in \pkg{paletteer}. +While the \code{\link[=data_color]{data_color()}} function allows us to flexibly color data cells in +our \pkg{gt} table, the harder part of this process is discovering and +choosing color palettes that are suitable for the table output. We can make +this process much easier in two ways: (1) by using the \pkg{paletteer} +package, which makes a wide range of palettes from various R packages readily +available, and (2) calling the \code{info_paletteer()} function to give us an +information table that serves as a quick reference for all of the discrete +color palettes available in \pkg{paletteer}. } \details{ The palettes displayed are organized by package and by palette name. These diff --git a/man/info_time_style.Rd b/man/info_time_style.Rd index d3bf4022ab..0a1482a3b6 100644 --- a/man/info_time_style.Rd +++ b/man/info_time_style.Rd @@ -7,11 +7,11 @@ info_time_style() } \description{ -The \code{fmt_time()} function lets us format time-based values in a -convenient manner using preset styles. The table generated by the -\code{info_time_style()} function provides a quick reference to all five -styles, with associated number codes, the format names, and example outputs -using a fixed time (\code{14:35}). +The \code{fmt_time()} function lets us format time-based values in a convenient +manner using preset styles. The table generated by the \code{info_time_style()} +function provides a quick reference to all five styles, with associated +number codes, the format names, and example outputs using a fixed time +(\code{14:35}). } \section{Figures}{ diff --git a/man/knit_print.gt_tbl.Rd b/man/knit_print.gt_tbl.Rd index 69301c8d40..ee42eaa2b6 100644 --- a/man/knit_print.gt_tbl.Rd +++ b/man/knit_print.gt_tbl.Rd @@ -7,7 +7,7 @@ knit_print.gt_tbl(x, ...) } \arguments{ -\item{x}{an object of class \code{gt_tbl}.} +\item{x}{An object of class \code{gt_tbl}.} } \description{ This facilitates printing of the HTML table within a knitr code chunk. diff --git a/man/local_image.Rd b/man/local_image.Rd index 2750ab7b7d..9bcff4fabf 100644 --- a/man/local_image.Rd +++ b/man/local_image.Rd @@ -7,38 +7,36 @@ local_image(file, height = 30) } \arguments{ -\item{file}{a path to an image file.} +\item{file}{A path to an image file.} -\item{height}{the absolute height (px) of the image in the table cell.} +\item{height}{The absolute height (px) of the image in the table cell.} } \value{ a character object with an HTML fragment that can be placed inside of - a cell. +a cell. } \description{ We can flexibly add a local image (i.e., an image residing on disk) inside of -a table with \code{local_image()} function. The function provides a -convenient way to generate an HTML fragment using an on-disk PNG or SVG. -Because this function is currently HTML-based, it is only useful for HTML -table output. To use this function inside of data cells, it is recommended -that the \code{\link{text_transform}()} function is used. With that function, -we can specify which data cells to target and then include a -\code{local_image()} call within the required user-defined function (for the -\code{fn} argument). If we want to include an image in other places (e.g., in -the header, within footnote text, etc.) we need to use \code{local_image()} -within the \code{\link{html}()} helper function. +a table with \code{local_image()} function. The function provides a convenient way +to generate an HTML fragment using an on-disk PNG or SVG. Because this +function is currently HTML-based, it is only useful for HTML table output. To +use this function inside of data cells, it is recommended that the +\code{\link[=text_transform]{text_transform()}} function is used. With that function, we can specify which +data cells to target and then include a \code{local_image()} call within the +required user-defined function (for the \code{fn} argument). If we want to include +an image in other places (e.g., in the header, within footnote text, etc.) we +need to use \code{local_image()} within the \code{\link[=html]{html()}} helper function. } \details{ By itself, the function creates an HTML image tag with an image URI embedded within. We can easily experiment with a local PNG or SVG image that's -available in the \pkg{gt} package using the \code{\link{test_image}()} -function. Using that, the call \code{local_image(file = test_image(type = -"png"))} evaluates to: +available in the \pkg{gt} package using the \code{\link[=test_image]{test_image()}} function. Using +that, the call \code{local_image(file = test_image(type = "png"))} evaluates to: \code{ src= style=\"height:30px;\">} -where a height of \code{30px} is a default height chosen to work well within -the heights of most table rows. +where a height of \code{30px} is a default height chosen to work well within the +heights of most table rows. } \section{Figures}{ diff --git a/man/location_cells.Rd b/man/location_cells.Rd index fec9154807..7f76fcb72a 100644 --- a/man/location_cells.Rd +++ b/man/location_cells.Rd @@ -26,10 +26,9 @@ cells_summary(groups = NULL, columns = NULL, rows = NULL) cells_grand_summary(columns = NULL, rows = NULL) } \arguments{ -\item{columns, rows, groups}{either a vector of names, a vector of -indices, values provided by \code{\link{vars}()}, values provided by -\code{c()}, or a select helper function (see Details for information on -these functions).} +\item{columns, rows, groups}{Either a vector of names, a vector of indices, +values provided by \code{\link[=vars]{vars()}}, values provided by \code{c()}, or a select helper +function (see Details for information on these functions).} } \value{ a list object of class \code{location_cells}. @@ -38,9 +37,9 @@ a list object of class \code{location_cells}. These helper functions are used to target individual cells in different locations (e.g., the stub, the column labels, the title, etc.). They can be used in any of these functions (which all have a \code{locations} argument): -\code{\link{tab_footnote}()}, \code{\link{tab_style}()}, and -\code{\link{text_transform}()} Furthermore, multiple locations can be -targeted by enclosing several \code{cells_*()} helper functions in a list. +\code{\link[=tab_footnote]{tab_footnote()}}, \code{\link[=tab_style]{tab_style()}}, and \code{\link[=text_transform]{text_transform()}} Furthermore, multiple +locations can be targeted by enclosing several \code{cells_*()} helper functions +in a list. } \details{ The following helper functions can be used to target cells (roughly in order diff --git a/man/md.Rd b/man/md.Rd index 18db87b6a0..4464d09bf5 100644 --- a/man/md.Rd +++ b/man/md.Rd @@ -7,11 +7,11 @@ md(text) } \arguments{ -\item{text}{the text that is understood to contain Markdown formatting.} +\item{text}{The text that is understood to contain Markdown formatting.} } \value{ -a character object that is tagged for a Markdown-to-HTML - transformation. +A character object that is tagged for a Markdown-to-HTML +transformation. a character object of class \code{from_markdown}. } diff --git a/man/pct.Rd b/man/pct.Rd index c5bee2254f..1433a9511c 100644 --- a/man/pct.Rd +++ b/man/pct.Rd @@ -8,7 +8,7 @@ pct(x) } \arguments{ \item{x}{the numeric value to format as a string percentage for some -\code{\link{tab_options}()} arguments that can take percentage values +\code{\link[=tab_options]{tab_options()}} arguments that can take percentage values (e.g., \code{table.width}).} } \description{ diff --git a/man/pizzaplace.Rd b/man/pizzaplace.Rd index 66b1e94ed5..1b83196480 100644 --- a/man/pizzaplace.Rd +++ b/man/pizzaplace.Rd @@ -6,22 +6,22 @@ \title{A year of pizza sales from a pizza place} \format{A tibble with 49574 rows and 7 variables: \describe{ - \item{id}{The ID for the order, which consists of one or more pizzas - at a give \code{date} and \code{time}} - \item{date}{A character representation of the \code{order} date, - expressed in the ISO 8601 date format (YYYY-MM-DD)} - \item{time}{A character representation of the \code{order} time, - expressed as a 24-hour time the ISO 8601 extended time format - (hh:mm:ss)} - \item{name}{The short name for the pizza} - \item{size}{The size of the pizza, which can either be \code{S}, - \code{M}, \code{L}, \code{XL} (rare!), or \code{XXL} (even rarer!); - most pizzas are available in the \code{S}, \code{M}, and \code{L} sizes - but exceptions apply} - \item{type}{The category or type of pizza, which can either be - \code{classic}, \code{chicken}, \code{supreme}, or \code{veggie}} - \item{price}{The price of the pizza and the amount that it sold for - (in USD)} +\item{id}{The ID for the order, which consists of one or more pizzas +at a give \code{date} and \code{time}} +\item{date}{A character representation of the \code{order} date, +expressed in the ISO 8601 date format (YYYY-MM-DD)} +\item{time}{A character representation of the \code{order} time, +expressed as a 24-hour time the ISO 8601 extended time format +(hh:mm:ss)} +\item{name}{The short name for the pizza} +\item{size}{The size of the pizza, which can either be \code{S}, +\code{M}, \code{L}, \code{XL} (rare!), or \code{XXL} (even rarer!); +most pizzas are available in the \code{S}, \code{M}, and \code{L} sizes +but exceptions apply} +\item{type}{The category or type of pizza, which can either be +\code{classic}, \code{chicken}, \code{supreme}, or \code{veggie}} +\item{price}{The price of the pizza and the amount that it sold for +(in USD)} }} \usage{ pizzaplace @@ -30,13 +30,13 @@ pizzaplace A synthetic dataset that describes pizza sales for a pizza place somewhere in the US. While the contents are artificial, the ingredients used to make the pizzas are far from it. There are 32 different pizzas that fall into 4 -different categories: \code{classic} (classic pizzas: 'You probably had one -like it before, but never like this!'), \code{chicken} (pizzas with chicken -as a major ingredient: 'Try the Southwest Chicken Pizza! You'll love it!'), -\code{supreme} (pizzas that try a little harder: 'My Soppressata pizza uses -only the finest salami from my personal salumist!'), and, \code{veggie} -(pizzas without any meats whatsoever: 'My Five Cheese pizza has so many -cheeses, I can only offer it in Large Size!'). +different categories: \code{classic} (classic pizzas: 'You probably had one like +it before, but never like this!'), \code{chicken} (pizzas with chicken as a major +ingredient: 'Try the Southwest Chicken Pizza! You'll love it!'), \code{supreme} +(pizzas that try a little harder: 'My Soppressata pizza uses only the finest +salami from my personal salumist!'), and, \code{veggie} (pizzas without any meats +whatsoever: 'My Five Cheese pizza has so many cheeses, I can only offer it in +Large Size!'). } \details{ Each pizza in the dataset is identified by a short \code{name}. The following @@ -80,7 +80,7 @@ Red Peppers, Mushrooms, Asiago Cheese, Alfredo Sauce) Supreme Pizzas: \itemize{ \item \code{brie_carre}: The Brie Carre Pizza (Brie Carre Cheese, Prosciutto, - Caramelized Onions, Pears, Thyme, Garlic) +Caramelized Onions, Pears, Thyme, Garlic) \item \code{calabrese}: The Calabrese Pizza (‘Nduja Salami, Pancetta, Tomatoes, Red Onions, Friggitello Peppers, Garlic) \item \code{soppressata}: The Soppressata Pizza (Soppressata Salami, Fontina diff --git a/man/print.gt_tbl.Rd b/man/print.gt_tbl.Rd index 962dbe26c7..f33052d278 100644 --- a/man/print.gt_tbl.Rd +++ b/man/print.gt_tbl.Rd @@ -7,7 +7,7 @@ \method{print}{gt_tbl}(x, ..., view = interactive()) } \arguments{ -\item{x}{an object of class \code{gt_tbl}.} +\item{x}{An object of class \code{gt_tbl}.} } \description{ This facilitates printing of the HTML table to the R console. diff --git a/man/px.Rd b/man/px.Rd index 5c6bf96cb0..027f7e2281 100644 --- a/man/px.Rd +++ b/man/px.Rd @@ -8,7 +8,7 @@ px(x) } \arguments{ \item{x}{the numeric value to format as a string (e.g., \code{"12px"}) for -some \code{\link{tab_options}()} arguments that can take values as units of +some \code{\link[=tab_options]{tab_options()}} arguments that can take values as units of pixels (e.g., \code{table.font.size}).} } \description{ diff --git a/man/render_gt.Rd b/man/render_gt.Rd index 2685ccf985..1b8c843b36 100644 --- a/man/render_gt.Rd +++ b/man/render_gt.Rd @@ -8,16 +8,16 @@ render_gt(expr, env = parent.frame(), quoted = FALSE, outputArgs = list()) } \arguments{ -\item{expr}{an expression that creates a \pkg{gt} table object.} +\item{expr}{An expression that creates a \pkg{gt} table object.} -\item{env}{the environment in which to evaluate the \code{expr}.} +\item{env}{The environment in which to evaluate the \code{expr}.} -\item{quoted}{is expr a quoted expression (with \code{quote()})? This is -useful if you want to save an expression in a variable.} +\item{quoted}{Is \code{expr`` a quoted expression (with }quote()`)? This is useful +if you want to save an expression in a variable.} \item{outputArgs}{A list of arguments to be passed through to the implicit -call to \code{\link{gt_output}()} when \code{render_gt} is used in an -interactive R Markdown document.} +call to \code{\link[=gt_output]{gt_output()}} when \code{render_gt} is used in an interactive R Markdown +document.} } \description{ A \pkg{gt} display table render function for use in Shiny diff --git a/man/row_group_order.Rd b/man/row_group_order.Rd index e19023ee7b..67d8479eb6 100644 --- a/man/row_group_order.Rd +++ b/man/row_group_order.Rd @@ -7,10 +7,9 @@ row_group_order(data, groups) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{groups}{a vector of row group names, or, a numeric vector of indices +\item{groups}{A vector of row group names, or, a numeric vector of indices corresponding to the new ordering. Either vector must correspond to assigned group names or the index positions. Also, either type of vector is not required to have all of the row group names or available index @@ -18,16 +17,16 @@ positions within it; any omitted values will be added to the end while preserving the original ordering.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ We can modify the display order of any row groups in a \pkg{gt} object with -the \code{row_group_order()} function. The \code{groups} argument can either -take a vector of row group names or a numeric vector of row group indices; -whichever is provided, the row groups will adhere to this revised ordering. -It isn't necessary to provide all row group names in \code{groups}, rather, -what is provided will assume the specified ordering at the top of the table -and the remaining row groups will follow in their original ordering. +the \code{row_group_order()} function. The \code{groups} argument can either take a +vector of row group names or a numeric vector of row group indices; whichever +is provided, the row groups will adhere to this revised ordering. It isn't +necessary to provide all row group names in \code{groups}, rather, what is +provided will assume the specified ordering at the top of the table and the +remaining row groups will follow in their original ordering. } \section{Figures}{ diff --git a/man/sp500.Rd b/man/sp500.Rd index 967ce05ba6..d694929c1a 100644 --- a/man/sp500.Rd +++ b/man/sp500.Rd @@ -6,14 +6,14 @@ \title{Daily S&P 500 Index data from 1950 to 2015} \format{A tibble with 16607 rows and 7 variables: \describe{ - \item{date}{The date expressed as \code{Date} values} - \item{open, high, low, close}{The day's opening, high, low, and closing - prices in USD; the \code{close} price is adjusted for splits} - \item{volume}{the number of trades for the given \code{date}} - \item{adj_close}{The close price adjusted for both dividends and splits} +\item{date}{The date expressed as \code{Date} values} +\item{open, high, low, close}{The day's opening, high, low, and closing +prices in USD; the \code{close} price is adjusted for splits} +\item{volume}{the number of trades for the given \code{date}} +\item{adj_close}{The close price adjusted for both dividends and splits} }} \source{ -Data collected from \url{https://finance.yahoo.com/quote/\%5EGSPC/history/}. +Data collected from \url{https://finance.yahoo.com/quote/\\\%5EGSPC/history/}. } \usage{ sp500 diff --git a/man/summary_rows.Rd b/man/summary_rows.Rd index 2ce924814c..6d709b9aa5 100644 --- a/man/summary_rows.Rd +++ b/man/summary_rows.Rd @@ -8,60 +8,56 @@ summary_rows(data, groups = NULL, columns = TRUE, fns, missing_text = "---", formatter = fmt_number, ...) } \arguments{ -\item{data}{A table object that is created using the \code{gt()} function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} \item{groups}{The groups to consider for generation of groupwise summary -rows. By default this is set to \code{NULL}, which results in the formation -of grand summary rows (a grand summary operates on all table data). -Providing the names of row groups in \code{c()} will create a groupwise -summary and generate summary rows for the specified groups. Setting this to -\code{TRUE} indicates that all available groups will receive groupwise -summary rows.} +rows. By default this is set to \code{NULL}, which results in the formation of +grand summary rows (a grand summary operates on all table data). Providing +the names of row groups in \code{\link[=c]{c()}} will create a groupwise summary and +generate summary rows for the specified groups. Setting this to \code{TRUE} +indicates that all available groups will receive groupwise summary rows.} \item{columns}{The columns for which the summaries should be calculated.} \item{fns}{Functions used for aggregations. This can include base functions -like \code{mean}, \code{min}, \code{max}, \code{median}, \code{sd}, or -\code{sum} or any other user-defined aggregation function. The function(s) -should be supplied within a \code{list()}. Within that list, we can specify -the functions by use of function names in quotes (e.g., \code{"sum"}), as -bare functions (e.g., \code{sum}), or as one-sided R formulas using a -leading \code{~}. In the formula representation, a \code{.} serves as the -data to be summarized (e.g., \code{sum(., na.rm = TRUE)}). The use of named -arguments is recommended as the names will serve as summary row labels for -the corresponding summary rows data (the labels can derived from the -function names but only when not providing bare function names).} +like \code{mean}, \code{min}, \code{max}, \code{median}, \code{sd}, or \code{sum} or any other +user-defined aggregation function. The function(s) should be supplied +within a \code{list()}. Within that list, we can specify the functions by use of +function names in quotes (e.g., \code{"sum"}), as bare functions (e.g., \code{sum}), +or as one-sided R formulas using a leading \code{~}. In the formula +representation, a \code{.} serves as the data to be summarized (e.g., \code{sum(., na.rm = TRUE)}). The use of named arguments is recommended as the names +will serve as summary row labels for the corresponding summary rows data +(the labels can derived from the function names but only when not providing +bare function names).} -\item{missing_text}{The text to be used in place of \code{NA} values in -summary cells with no data outputs.} +\item{missing_text}{The text to be used in place of \code{NA} values in summary +cells with no data outputs.} -\item{formatter}{A formatter function name. These can be any of the -\code{fmt_*()}functions available in the package (e.g., -\code{\link{fmt_number}()}, \code{link{fmt_percent}()}, etc.), or a custom -function using \code{\link{fmt}()}. The default function is -\code{\link{fmt_number}()} and its options can be accessed through -\code{...}.} +\item{formatter}{A formatter function name. These can be any of the \code{fmt_*()} +functions available in the package (e.g., \code{\link[=fmt_number]{fmt_number()}}, \code{\link[=fmt_percent]{fmt_percent()}}, +etc.), or a custom function using \code{fmt()}. The default function is +\code{\link[=fmt_number]{fmt_number()}} and its options can be accessed through \code{...}.} \item{...}{Values passed to the \code{formatter} function, where the provided values are to be in the form of named vectors. For example, when using the -default \code{formatter} function, \code{\link{fmt_number}()}, options such -as \code{decimals}, \code{use_seps}, and \code{locale} can be used.} +default \code{formatter} function, \code{\link[=fmt_number]{fmt_number()}}, options such as \code{decimals}, +\code{use_seps}, and \code{locale} can be used.} } \value{ An object of class \code{gt_tbl}. } \description{ Add groupwise summary rows to one or more row groups by using the input data -already provided in the \code{\link{gt}()} function alongside any suitable -aggregation functions. Or, add a grand summary that incorporates all -available data, regardless of grouping. You choose how to format the values -in the resulting summary cells by use of a \code{formatter} function (e.g, -\code{\link{fmt_number}()}) and any relevant options. +already provided in the \code{\link[=gt]{gt()}} function alongside any suitable aggregation +functions. Or, add a grand summary that incorporates all available data, +regardless of grouping. You choose how to format the values in the resulting +summary cells by use of a \code{formatter} function (e.g, \code{fmt_number}) and any +relevant options. } \details{ Should we need to obtain the summary data for external purposes, the -\code{\link{extract_summary}()} function can be used with a \code{gt_tbl} -object where summary rows were added via \code{summary_rows()}. +\code{\link[=extract_summary]{extract_summary()}} function can be used with a \code{gt_tbl} object where summary +rows were added via \code{summary_rows()}. } \section{Figures}{ diff --git a/man/sza.Rd b/man/sza.Rd index 085eca45b3..f9b9319b37 100644 --- a/man/sza.Rd +++ b/man/sza.Rd @@ -6,13 +6,13 @@ \title{Twice hourly solar zenith angles by month & latitude} \format{A tibble with 816 rows and 4 variables: \describe{ - \item{latitude}{The latitude in decimal degrees for the observations} - \item{month}{The measurement month; all calculations where conducted - for the first day of each month} - \item{tst}{The true solar time at the given \code{latitude} and date - (first of \code{month}) for which the solar zenith angle is calculated} - \item{sza}{The solar zenith angle in degrees, where \code{NA}s - indicate that sunrise hadn't yet occurred by the \code{tst} value} +\item{latitude}{The latitude in decimal degrees for the observations} +\item{month}{The measurement month; all calculations where conducted +for the first day of each month} +\item{tst}{The true solar time at the given \code{latitude} and date +(first of \code{month}) for which the solar zenith angle is calculated} +\item{sza}{The solar zenith angle in degrees, where \code{NA}s +indicate that sunrise hadn't yet occurred by the \code{tst} value} }} \source{ Calculated Actinic Fluxes (290 - 700 nm) for Air Pollution diff --git a/man/tab_footnote.Rd b/man/tab_footnote.Rd index d9644360da..ab725ab990 100644 --- a/man/tab_footnote.Rd +++ b/man/tab_footnote.Rd @@ -7,54 +7,46 @@ tab_footnote(data, footnote, locations) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{footnote}{the text to be used in the footnote. We can optionally use -the \code{\link{md}()} and \code{\link{html}()} functions to style the text -as Markdown or to retain HTML elements in the footnote text.} +\item{footnote}{The text to be used in the footnote. We can optionally use +the \code{\link[=md]{md()}} and \code{\link[=html]{html()}} functions to style the text as Markdown or to +retain HTML elements in the footnote text.} -\item{locations}{the cell or set of cells to be associated with the footnote. -Supplying any of the \code{cells_*()} helper functions is a useful way to -target the location cells that are associated with the footnote text. These -helper functions are: \code{\link{cells_title}()}, -\code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -\code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -\code{\link{cells_summary}()}. Please see the help article -\link{location_cells} for more information on how these helper functions -can be used. Additionally, we can enclose several \code{cells_*()} calls -within a \code{list()} if we wish to link the footnote text to different +\item{locations}{The cell or set of cells to be associated with the footnote. +Supplying any of the \code{cells_*()} helper functions is a useful way to target +the location cells that are associated with the footnote text. These helper +functions are: \code{\link[=cells_title]{cells_title()}}, \code{\link[=cells_column_labels]{cells_column_labels()}}, \code{\link[=cells_group]{cells_group()}}, +\code{\link[=cells_stub]{cells_stub()}}, \code{\link[=cells_data]{cells_data()}}, and \code{\link[=cells_summary]{cells_summary()}}. Please see the help +article \link{location_cells} for more information on how these helper +functions can be used. Additionally, we can enclose several \code{cells_*()} +calls within a \code{list()} if we wish to link the footnote text to different types of locations (e.g., cell data values, stub group headings, the table title, etc.).} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ The \code{tab_footnote()} function can make it a painless process to add a footnote to a \pkg{gt} table. There are two components to a footnote: (1) a glyph that is attached to the targeted cell text, and (2) the footnote text (that starts with the corresponding glyph) that is placed in the table's -footer area. Each call of \code{tab_footnote()} will add a different note, -and one or more cells can be targeted via the location helper functions -(e.g., \code{\link{cells_data}()}, \code{\link{cells_column_labels}()}, -etc.). +footer area. Each call of \code{tab_footnote()} will add a different note, and one +or more cells can be targeted via the location helper functions (e.g., +\code{\link[=cells_data]{cells_data()}}, \code{\link[=cells_column_labels]{cells_column_labels()}}, etc.). } \details{ The formatting of the footnotes can be controlled through the use of various -parameters in the \code{\link{tab_options}()} function: +parameters in the \code{\link[=tab_options]{tab_options()}} function: -\itemize{ -\item \code{footnote.sep}: allows for a choice of the separator between +\itemize{ \item \code{footnote.sep}: allows for a choice of the separator between consecutive footnotes in the table footer. By default, this is set to a -linebreak. -\item \code{footnote.glyph}: the set of sequential characters or numbers -used to identify the footnotes. -\item \code{footnote.font.size}: the size of the font used in the footnote -section. -\item \code{footnote.padding}: the amount of padding to apply between the -footnote and source note sections in the table footer. -} +linebreak. \item \code{footnote.glyph}: the set of sequential characters or +numbers used to identify the footnotes. \item \code{footnote.font.size}: the size +of the font used in the footnote section. \item \code{footnote.padding}: the +amount of padding to apply between the footnote and source note sections in +the table footer. } } \section{Figures}{ diff --git a/man/tab_header.Rd b/man/tab_header.Rd index 9c76a43d97..37118eff40 100644 --- a/man/tab_header.Rd +++ b/man/tab_header.Rd @@ -7,16 +7,15 @@ tab_header(data, title, subtitle = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{title, subtitle}{text to be used in the table title and, optionally, for -the table subtitle. We can elect to use the \code{\link{md}()} and -\code{\link{html}()} helper functions to style the text as Markdown or to -retain HTML elements in the text.} +\item{title, subtitle}{Text to be used in the table title and, optionally, for +the table subtitle. We can elect to use the \code{\link[=md]{md()}} and \code{\link[=html]{html()}} helper +functions to style the text as Markdown or to retain HTML elements in the +text.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ We can add a table header to the \pkg{gt} table with a title and even a diff --git a/man/tab_options.Rd b/man/tab_options.Rd index e0ea146906..3b479633c5 100644 --- a/man/tab_options.Rd +++ b/man/tab_options.Rd @@ -38,45 +38,42 @@ tab_options(data, table.width = NULL, table.font.size = NULL, row.striping.include_table_body = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{table.width}{the width of the table. Can be specified as a +\item{table.width}{The width of the table. Can be specified as a single-length character with units of pixels or as a percentage. If provided as a single-length numeric vector, it is assumed that the value is -given in units of pixels. The \code{\link{px}()} and \code{\link{pct}()} -helper functions can also be used to pass in numeric values and obtain -values as pixel or percent units.} - -\item{table.font.size, heading.title.font.size, heading.subtitle.font.size, column_labels.font.size, row_group.font.size, footnote.font.size, sourcenote.font.size}{font sizes for the parent text element \code{table} and the following child -elements: \code{heading.title}, \code{heading.subtitle}, \code{columns}, -\code{row_group}, \code{footnote}, and \code{sourcenote}. Can be specified -as a single-length character vector with units of pixels (e.g., -\code{12px}) or as a percentage (e.g., \code{80\%}). If provided as a -single-length numeric vector, it is assumed that the value is given in -units of pixels. The \code{\link{px}()} and \code{\link{pct}()} helper +given in units of pixels. The \code{\link[=px]{px()}} and \code{\link[=pct]{pct()}} helper functions can also +be used to pass in numeric values and obtain values as pixel or percent +units.} + +\item{table.font.size, heading.title.font.size, heading.subtitle.font.size, column_labels.font.size, row_group.font.size, footnote.font.size, sourcenote.font.size}{Font sizes for the parent text element \code{table} and the following child +elements: \code{heading.title}, \code{heading.subtitle}, \code{columns}, \code{row_group}, +\code{footnote}, and \code{sourcenote}. Can be specified as a single-length character +vector with units of pixels (e.g., \code{12px}) or as a percentage (e.g., +\code{80\\\%}). If provided as a single-length numeric vector, it is assumed that +the value is given in units of pixels. The \code{\link[=px]{px()}} and \code{\link[=pct]{pct()}} helper functions can also be used to pass in numeric values and obtain values as pixel or percent units.} -\item{table.background.color, heading.background.color, column_labels.background.color, row_group.background.color, summary_row.background.color, grand_summary_row.background.color}{background colors for the parent element \code{table} and the following -child elements: \code{heading}, \code{columns}, \code{row_group}, -\code{summary_row}, and \code{table_body}. A color name or a hexadecimal -color code should be provided.} +\item{table.background.color, heading.background.color, column_labels.background.color, row_group.background.color, summary_row.background.color, grand_summary_row.background.color}{background colors for the parent element \code{table} and the following child +elements: \code{heading}, \code{columns}, \code{row_group}, \code{summary_row}, and +\code{table_body}. A color name or a hexadecimal color code should be provided.} -\item{table.border.top.style, table.border.top.width, table.border.top.color}{the style, width, and color of the table's top border.} +\item{table.border.top.style, table.border.top.width, table.border.top.color}{The style, width, and color of the table's top border.} -\item{heading.border.bottom.style, heading.border.bottom.width, heading.border.bottom.color}{the style, width, and color of the heading's bottom border.} +\item{heading.border.bottom.style, heading.border.bottom.width, heading.border.bottom.color}{The style, width, and color of the heading's bottom border.} \item{column_labels.font.weight, row_group.font.weight}{the font weight of the \code{columns} and \code{row_group} text element.} -\item{column_labels.hidden}{an option to hide the column labels.} +\item{column_labels.hidden}{An option to hide the column labels.} -\item{row_group.border.top.style, row_group.border.top.width, row_group.border.top.color}{the style, width, and color of the row group's top border.} +\item{row_group.border.top.style, row_group.border.top.width, row_group.border.top.color}{The style, width, and color of the row group's top border.} -\item{row_group.border.bottom.style, row_group.border.bottom.width, row_group.border.bottom.color}{the style, width, and color of the row group's bottom border.} +\item{row_group.border.bottom.style, row_group.border.bottom.width, row_group.border.bottom.color}{The style, width, and color of the row group's bottom border.} -\item{table_body.border.top.style, table_body.border.top.width, table_body.border.top.color}{the style, width, and color of the table body's top border.} +\item{table_body.border.top.style, table_body.border.top.width, table_body.border.top.color}{The style, width, and color of the table body's top border.} \item{table_body.border.bottom.style, table_body.border.bottom.width, table_body.border.bottom.color}{the style, width, and color of the table body's bottom border.} @@ -89,22 +86,22 @@ to apply text transformations to the label text in each summary row.} \item{footnote.sep}{the separating characters between adjacent footnotes in the footnotes section. The default value produces a linebreak.} -\item{footnote.glyph}{the set of sequential figures or characters used to -identify the footnotes. We can either supply the keyword \code{"numbers"} -(the default, indicating that we want numeric glyphs), the keywords -\code{"letters"} or \code{"LETTERS"} (indicating that we want letters as -glyphs, either lowercase or uppercase), or, a vector of character values -representing the series of glyphs. A series of glyphs is recycled when its -usage goes beyond the length of the set. At each cycle, the glyphs are -simply combined (e.g., \code{*} -> \code{**} -> \code{***}).} +\item{footnote.glyph}{The set of sequential figures or characters used to +identify the footnotes. We can either supply the keyword \code{"numbers"} (the +default, indicating that we want numeric glyphs), the keywords \code{"letters"} +or \code{"LETTERS"} (indicating that we want letters as glyphs, either lowercase +or uppercase), or, a vector of character values representing the series of +glyphs. A series of glyphs is recycled when its usage goes beyond the +length of the set. At each cycle, the glyphs are simply combined (e.g., \code{*} +-> \code{**} -> \code{***}).} -\item{footnote.padding, sourcenote.padding}{the amount of padding to apply to +\item{footnote.padding, sourcenote.padding}{The amount of padding to apply to the footnote and source note sections.} -\item{row.striping.include_stub}{an option for whether to include the stub +\item{row.striping.include_stub}{An option for whether to include the stub when striping rows.} -\item{row.striping.include_table_body}{an option for whether to include the +\item{row.striping.include_table_body}{An option for whether to include the table body when striping rows.} } \value{ diff --git a/man/tab_row_group.Rd b/man/tab_row_group.Rd index 43c897fb26..b40195ce1d 100644 --- a/man/tab_row_group.Rd +++ b/man/tab_row_group.Rd @@ -7,30 +7,28 @@ tab_row_group(data, group = NULL, rows = NULL, others = NULL) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{group}{the name of the row group. This text will also serve as the row +\item{group}{The name of the row group. This text will also serve as the row group label.} -\item{rows}{the rows to be made components of the row group. Can either be a -vector of row captions provided \code{c()}, a vector of row indices, or a -helper function focused on selections. The select helper functions are: -\code{\link{starts_with}()}, \code{\link{ends_with}()}, -\code{\link{contains}()}, \code{\link{matches}()}, \code{\link{one_of}()}, -and \code{\link{everything}()}.} +\item{rows}{The rows to be made components of the row group. Can either be a +vector of row captions provided \code{c()}, a vector of row indices, or a helper +function focused on selections. The select helper functions are: +\code{\link[=starts_with]{starts_with()}}, \code{\link[=ends_with]{ends_with()}}, \code{\link[=contains]{contains()}}, \code{\link[=matches]{matches()}}, \code{\link[=one_of]{one_of()}}, and +\code{\link[=everything]{everything()}}.} -\item{others}{an option to set a default row group label for any rows not +\item{others}{An option to set a default row group label for any rows not formally placed in a row group named by \code{group} in any call of -\code{tab_row_group()}. A separate call to \code{tab_row_group()} with only -a value to \code{others} is possible and makes explicit that the call is -meant to provide a default row group label. If this is not set and -there are rows that haven't been placed into a row group (where one or -more row groups already exist), those rows will be automatically placed into -a row group without a label.} +\code{tab_row_group()}. A separate call to \code{tab_row_group()} with only a value +to \code{others} is possible and makes explicit that the call is meant to +provide a default row group label. If this is not set and there are rows +that haven't been placed into a row group (where one or more row groups +already exist), those rows will be automatically placed into a row group +without a label.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Create a row group with a collection of rows. This requires specification of diff --git a/man/tab_source_note.Rd b/man/tab_source_note.Rd index 00467ad610..1f82c4a753 100644 --- a/man/tab_source_note.Rd +++ b/man/tab_source_note.Rd @@ -7,23 +7,21 @@ tab_source_note(data, source_note) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{source_note}{text to be used in the source note. We can optionally use -the \code{\link{md}()} and \code{\link{html}()} functions to style the text -as Markdown or to retain HTML elements in the text.} +\item{source_note}{Text to be used in the source note. We can optionally use +the \code{\link[=md]{md()}} and \code{\link[=html]{html()}} functions to style the text as Markdown or to +retain HTML elements in the text.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Add a source note to the footer part of the \pkg{gt} table. A source note is useful for citing the data included in the table. Several can be added to the -footer, simply use multiple calls of \code{tab_source_note()} and they will -be inserted in the order provided. We can use Markdown formatting for the -note, or, if the table is intended for HTML output, we can include HTML -formatting. +footer, simply use multiple calls of \code{tab_source_note()} and they will be +inserted in the order provided. We can use Markdown formatting for the note, +or, if the table is intended for HTML output, we can include HTML formatting. } \section{Figures}{ diff --git a/man/tab_spanner.Rd b/man/tab_spanner.Rd index ccf94a1d4b..66a422856f 100644 --- a/man/tab_spanner.Rd +++ b/man/tab_spanner.Rd @@ -7,19 +7,18 @@ tab_spanner(data, label, columns, gather = TRUE) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{label}{the text to use for the spanner column label.} +\item{label}{The text to use for the spanner column label.} -\item{columns}{the columns to be components of the spanner heading.} +\item{columns}{The columns to be components of the spanner heading.} -\item{gather}{an option to move the specified \code{columns} such that they -are unified under the spanner column label. Ordering of the -moved-into-place columns will be preserved in all cases.} +\item{gather}{An option to move the specified \code{columns} such that they are +unified under the spanner column label. Ordering of the moved-into-place +columns will be preserved in all cases.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Set a spanner column label by mapping it to columns already in the table. diff --git a/man/tab_stubhead_label.Rd b/man/tab_stubhead_label.Rd index 9e1156e9ad..ef9fefd3d3 100644 --- a/man/tab_stubhead_label.Rd +++ b/man/tab_stubhead_label.Rd @@ -7,15 +7,14 @@ tab_stubhead_label(data, label) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{label}{the text to be used as the stubhead label We can optionally -use the \code{\link{md}()} and \code{\link{html}()} functions to style the -text as Markdown or to retain HTML elements in the text.} +\item{label}{The text to be used as the stubhead label We can optionally use +the \code{\link[=md]{md()}} and \code{\link[=html]{html()}} functions to style the text as Markdown or to +retain HTML elements in the text.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Add a label to the stubhead of a \pkg{gt} table. The stubhead is the lone diff --git a/man/tab_style.Rd b/man/tab_style.Rd index 5d0f9d6584..900ee04d3e 100644 --- a/man/tab_style.Rd +++ b/man/tab_style.Rd @@ -7,19 +7,18 @@ tab_style(data, style, locations) } \arguments{ -\item{data}{A table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{style}{a vector of styles to use. The \code{\link{cells_styles}()} +\item{style}{a vector of styles to use. The \code{\link[=cells_styles]{cells_styles()}} helper function can be used here to more easily generate valid styles.} \item{locations}{the cell or set of cells to be associated with the style Supplying any of the \code{cells_*()} helper functions is a useful way to target the location cells that are associated with the style application. -These helper functions are: \code{\link{cells_title}()}, -\code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -\code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -\code{\link{cells_summary}()}. Please see the help article +These helper functions are: \code{\link[=cells_title]{cells_title()}}, +\code{\link[=cells_column_labels]{cells_column_labels()}}, \code{\link[=cells_group]{cells_group()}}, +\code{\link[=cells_stub]{cells_stub()}}, \code{\link[=cells_data]{cells_data()}}, and +\code{\link[=cells_summary]{cells_summary()}}. Please see the help article \link{location_cells} for more information on how these helper functions can be used. Additionally, we can enclose several \code{cells_*()} calls within a \code{list()} if we wish to apply styles to different types of @@ -32,10 +31,10 @@ an object of class \code{gt_tbl}. \description{ With the \code{tab_style()} function we can target specific cells and apply styles to them. This is best done in conjunction with the -\code{\link{cells_styles}()} helper function. At present this function is +\code{\link[=cells_styles]{cells_styles()}} helper function. At present this function is focused on the application of styles for HTML output only (as such, other output formats will ignore all \code{tab_style()} calls). With the help of -\code{\link{cells_styles}()}, we can set the following styles: +\code{\link[=cells_styles]{cells_styles()}}, we can set the following styles: \itemize{ \item the background color of the cell (\code{bkgd_color}) \item the cell's text color (\code{text_color}), font (\code{text_font}), or @@ -118,9 +117,9 @@ tab_2 <- } \seealso{ -\code{\link{cells_styles}()} as a helper for defining custom styles - and \code{\link{cells_data}()} as a useful helper function for targeting - one or more data cells to be styled. +\code{\link[=cells_styles]{cells_styles()}} as a helper for defining custom styles +and \code{\link[=cells_data]{cells_data()}} as a useful helper function for targeting +one or more data cells to be styled. Other table-part creation/modification functions: \code{\link{gt_preview}}, \code{\link{gt}}, \code{\link{tab_footnote}}, diff --git a/man/test_image.Rd b/man/test_image.Rd index 30068001ea..de394fc7ff 100644 --- a/man/test_image.Rd +++ b/man/test_image.Rd @@ -7,15 +7,14 @@ test_image(type = c("png", "svg")) } \arguments{ -\item{type}{the type of the image, which can either be \code{png} (the -default) or \code{svg}.} +\item{type}{The type of the image, which can either be \code{png} (the default) or +\code{svg}.} } \description{ Two test images are available within the \pkg{gt} package. Both contain the same imagery (sized at 200px by 200px) but one is a PNG file while the other -is an SVG file. This function is most useful when paired with -\code{\link{local_image}()} since we test various sizes of the test image -within that function. +is an SVG file. This function is most useful when paired with \code{\link[=local_image]{local_image()}} +since we test various sizes of the test image within that function. } \seealso{ Other image addition functions: \code{\link{ggplot_image}}, diff --git a/man/text_transform.Rd b/man/text_transform.Rd index 1fbe7bea41..da229fb5d0 100644 --- a/man/text_transform.Rd +++ b/man/text_transform.Rd @@ -7,26 +7,23 @@ text_transform(data, locations, fn) } \arguments{ -\item{data}{a table object that is created using the \code{\link{gt}()} -function.} +\item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} -\item{locations}{the cell or set of cells to be associated with the text +\item{locations}{The cell or set of cells to be associated with the text transformation. Supplying any of the \code{cells_*()} helper functions is a useful way to target the location cells that are associated with the -footnote text. These helper functions are: \code{\link{cells_title}()}, -\code{\link{cells_column_labels}()}, \code{\link{cells_group}()}, -\code{\link{cells_stub}()}, \code{\link{cells_data}()}, and -\code{\link{cells_summary}()}. Please see the help article -\link{location_cells} for more information on how these helper functions -can be used. Additionally, we can enclose several \code{cells_*()} calls -within a \code{list()} if we wish to link the footnote text to different -types of locations (e.g., cell data values, stub group headings, the table -title, etc.).} +footnote text. These helper functions are: \code{\link[=cells_title]{cells_title()}}, +\code{\link[=cells_column_labels]{cells_column_labels()}}, \code{\link[=cells_group]{cells_group()}}, \code{\link[=cells_stub]{cells_stub()}}, \code{\link[=cells_data]{cells_data()}}, +and \code{\link[=cells_summary]{cells_summary()}}. Please see the help article \link{location_cells} +for more information on how these helper functions can be used. +Additionally, we can enclose several \code{cells_*()} calls within a \code{list()} if +we wish to link the footnote text to different types of locations (e.g., +cell data values, stub group headings, the table title, etc.).} -\item{fn}{the function to use for text transformation.} +\item{fn}{The function to use for text transformation.} } \value{ -an object of class \code{gt_tbl}. +An object of class \code{gt_tbl}. } \description{ Perform targeted text transformation with a function diff --git a/man/web_image.Rd b/man/web_image.Rd index 64f18f403a..0f0b76bf10 100644 --- a/man/web_image.Rd +++ b/man/web_image.Rd @@ -7,25 +7,25 @@ web_image(url, height = 30) } \arguments{ -\item{url}{a url that resolves to an image file.} +\item{url}{A url that resolves to an image file.} -\item{height}{the absolute height (px) of the image in the table cell.} +\item{height}{The absolute height (px) of the image in the table cell.} } \value{ -a character object with an HTML fragment that can be placed inside of - a cell. +A character object with an HTML fragment that can be placed inside of +a cell. } \description{ We can flexibly add a web image inside of a table with \code{web_image()} function. The function provides a convenient way to generate an HTML fragment with an image URL. Because this function is currently HTML-based, it is only useful for HTML table output. To use this function inside of data cells, it -is recommended that the \code{\link{text_transform}()} function is used. With -that function, we can specify which data cells to target and then include a -\code{web_image()} call within the required user-defined function (for the -\code{fn} argument). If we want to include an image in other places (e.g., in -the header, within footnote text, etc.) we need to use \code{web_image()} -within the \code{\link{html}()} helper function. +is recommended that the \code{\link[=text_transform]{text_transform()}} function is used. With that +function, we can specify which data cells to target and then include a +\code{web_image()} call within the required user-defined function (for the \code{fn} +argument). If we want to include an image in other places (e.g., in the +header, within footnote text, etc.) we need to use \code{web_image()} within the +\code{\link[=html]{html()}} helper function. } \details{ By itself, the function creates an HTML image tag, so, the call @@ -33,8 +33,8 @@ By itself, the function creates an HTML image tag, so, the call \code{} -where a height of \code{30px} is a default height chosen to work well within -the heights of most table rows. +where a height of \code{30px} is a default height chosen to work well within the +heights of most table rows. } \section{Figures}{ From 38f0d3a23f940b411f78f2bfa8a9da0cc87806e5 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Fri, 26 Apr 2019 21:37:26 -0400 Subject: [PATCH 7/8] Rewritten vignette for adding summary rows (#273) * Update the `creating-summary-lines` vignette * Update the `creating-summary-lines` vignette * Make minor modifications to text * Remove use of `md()` in column spanner label * Modify roxygen documentation * Add to NAMESPACE * Update help file using roxygen * Modify pkgdown YAML file * Update vignette on creating summaries --- NAMESPACE | 1 + R/summary_rows.R | 33 +- _pkgdown.yml | 8 +- man/summary_rows.Rd | 17 +- vignettes/case-study-gtcars.Rmd | 4 +- vignettes/creating-summary-lines.Rmd | 523 +++++++++++++++------------ 6 files changed, 341 insertions(+), 245 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 096f6d8a7e..3f66b980d0 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -42,6 +42,7 @@ export(fmt_percent) export(fmt_scientific) export(fmt_time) export(ggplot_image) +export(grand_summary_rows) export(gt) export(gt_latex_dependencies) export(gt_output) diff --git a/R/summary_rows.R b/R/summary_rows.R index 0d8742af9b..885d8b3157 100644 --- a/R/summary_rows.R +++ b/R/summary_rows.R @@ -1,11 +1,12 @@ #' Add summary rows using aggregation functions #' -#' Add groupwise summary rows to one or more row groups by using the input data -#' already provided in the [gt()] function alongside any suitable aggregation -#' functions. Or, add a grand summary that incorporates all available data, -#' regardless of grouping. You choose how to format the values in the resulting -#' summary cells by use of a `formatter` function (e.g, `fmt_number`) and any -#' relevant options. +#' Add groupwise summary rows (with `summary_rows()`) to one or more row groups +#' by using the input data already provided in the [gt()] function alongside any +#' suitable aggregation functions. Or, add a grand summary (with +#' `grand_summary_rows()`) that incorporates all available data, regardless of +#' grouping. You choose how to format the values in the resulting summary cells +#' by use of a `formatter` function (e.g, `fmt_number`) and any relevant +#' options. #' #' Should we need to obtain the summary data for external purposes, the #' [extract_summary()] function can be used with a `gt_tbl` object where summary @@ -77,6 +78,7 @@ #' \if{html}{\figure{man_summary_rows_1.svg}{options: width=100\%}} #' #' @family row addition functions +#' @rdname summary_rows #' @export summary_rows <- function(data, groups = NULL, @@ -147,6 +149,25 @@ summary_rows <- function(data, data } +#' @rdname summary_rows +#' @export +grand_summary_rows <- function(data, + columns = TRUE, + fns, + missing_text = "---", + formatter = fmt_number, + ...) { + + summary_rows( + data, + groups = NULL, + columns = columns, + fns = fns, + missing_text = missing_text, + formatter = formatter, + ...) +} + add_summary_location_row <- function(loc, data, text, diff --git a/_pkgdown.yml b/_pkgdown.yml index 744d218958..33840ee292 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -115,12 +115,12 @@ reference: RStudio Cloud Example

- There is one function that will add rows to a **gt** table and that - is the `summary_rows()` function. It's useful for adding summary rows - to any table that has row groups and a stub (which is required for - summary row labels). + There are two function that will add rows to a **gt** table: + `summary_rows()` and `grand_summary_rows()`. These are useful for adding + groupwise and grand summary rows. contents: - summary_rows + - grand_summary_rows - title: Export Table desc: > diff --git a/man/summary_rows.Rd b/man/summary_rows.Rd index 6d709b9aa5..02a32ba5c2 100644 --- a/man/summary_rows.Rd +++ b/man/summary_rows.Rd @@ -2,10 +2,14 @@ % Please edit documentation in R/summary_rows.R \name{summary_rows} \alias{summary_rows} +\alias{grand_summary_rows} \title{Add summary rows using aggregation functions} \usage{ summary_rows(data, groups = NULL, columns = TRUE, fns, missing_text = "---", formatter = fmt_number, ...) + +grand_summary_rows(data, columns = TRUE, fns, missing_text = "---", + formatter = fmt_number, ...) } \arguments{ \item{data}{A table object that is created using the \code{\link[=gt]{gt()}} function.} @@ -47,12 +51,13 @@ default \code{formatter} function, \code{\link[=fmt_number]{fmt_number()}}, opti An object of class \code{gt_tbl}. } \description{ -Add groupwise summary rows to one or more row groups by using the input data -already provided in the \code{\link[=gt]{gt()}} function alongside any suitable aggregation -functions. Or, add a grand summary that incorporates all available data, -regardless of grouping. You choose how to format the values in the resulting -summary cells by use of a \code{formatter} function (e.g, \code{fmt_number}) and any -relevant options. +Add groupwise summary rows (with \code{summary_rows()}) to one or more row groups +by using the input data already provided in the \code{\link[=gt]{gt()}} function alongside any +suitable aggregation functions. Or, add a grand summary (with +\code{grand_summary_rows()}) that incorporates all available data, regardless of +grouping. You choose how to format the values in the resulting summary cells +by use of a \code{formatter} function (e.g, \code{fmt_number}) and any relevant +options. } \details{ Should we need to obtain the summary data for external purposes, the diff --git a/vignettes/case-study-gtcars.Rmd b/vignettes/case-study-gtcars.Rmd index cabf9e4ae7..b420ebf543 100644 --- a/vignettes/case-study-gtcars.Rmd +++ b/vignettes/case-study-gtcars.Rmd @@ -141,7 +141,7 @@ Here, we'll put the `mpg_c`, `mpg_h`, `hp`, `hp_rpm`, `trq`, `trq_rpm` columns u tab <- tab %>% tab_spanner( - label = md("*Performance*"), + label = "Performance", columns = vars(mpg_c, mpg_h, hp, hp_rpm, trq, trq_rpm) ) @@ -370,7 +370,7 @@ tab <- after = vars(trim) ) %>% tab_spanner( - label = md("*Performance*"), + label = "Performance", columns = vars(mpg_c, mpg_h, hp, hp_rpm, trq, trq_rpm) ) %>% cols_merge( diff --git a/vignettes/creating-summary-lines.Rmd b/vignettes/creating-summary-lines.Rmd index 1e28e15e91..8be2cc2cd9 100644 --- a/vignettes/creating-summary-lines.Rmd +++ b/vignettes/creating-summary-lines.Rmd @@ -16,227 +16,371 @@ library(gt) library(dplyr) ``` -Tables with summary data are quite common and naturally occur with alarming regularity. We can use **gt** to produce such summary components. These summary rows are automatically inserted within the relevant row groups, where each summary row is the result of a different aggregation function. +We can use the **gt** `summary_rows()` function to insert summary rows into a table. There are two main types of summary rows: (1) groupwise summaries, and (2) the grand summary. The groupwise summaries operate on one or more row groups, which can themselves be generated in a variety of ways: -### Preparing the Input Data Table +- with the `gt()` function's `groupname_col` option +- using the `tab_row_group()` function on a gt object +- by passing in a grouped `tbl_df` object to `gt()` (using `dplyr::group_by()`) -To most easily insert the necessary summary rows, we need to ensure that some preparatory work is done. The key change to the input data table should be to have a `groupname` column present, with categorical group names for each grouping. The following example data table contains both `groupname` and `rowname` columns, along with two data columns (named `value_1` and `value_2`). Having the magic column names `groupname` and `rowname` will signal to **gt** that they should be used to form a table stub where `groupname` collects rows into a row group (furnishing a group heading row above), and `rowname` provides row labels within each row group. Here is a diagram showing the restructuring: +We generate the summary data through specification of aggregation functions. You choose how to format the values in the resulting summary cells by use of a formatter function (e.g, +`fmt_number()`) and any relevant options. These summary rows are automatically inserted within the relevant row groups (for groupwise summaries) or at the bottom of the table (as a grand summary), where each summary row is the result of a different aggregation function. -The incoming data table for the purpose of the first example will be created using `dplyr::tribble()`: +### Preparing the Input Data Table -```{r} -# Create a table that creates a stub and -# row groups by virtue of having `groupname` -# and `rowname` columns -tbl <- - dplyr::tribble( - ~groupname, ~rowname, ~value_1, ~value_2, - "A", "1", 235.6, 260.1, - "A", "2", 184.3, 84.4, - "A", "3", 342.3, 126.3, - "A", "4", 234.9, 83.0, - "B", "1", 190.9, 832.5, - "B", "2", 743.3, 281.2, - "B", "3", 252.3, 732.5, - "B", "4", 344.7, 546.1, - "C", "1", 197.2, 818.0, - "C", "2", 284.3, 394.4, - ) +Let's use the `exibble` dataset (included in the **gt** package) to demonstrate how summary rows can be added. That table contains categorical columns named `row` and `group`, along several columns with varying data types. Here is a preview of the `exibble` dataset using solely the `gt()` function with no other options: + +```{r exibble_preview_gt} +exibble %>% gt() ``` -There are three groups in this data table: `A`, `B`, and `C`. The presence of the `groupname` column will tell **gt** to partition the stub into three row groups. This is how the **gt** display table appears after simply providing `tbl` to `gt()`: +We'll create a table stub with both row labels (using the `row` column) and row groups (using the `group` column). The end result will be a table organized with labeled rows that are grouped together (the row group labels identify each of the row groups). To make the examples a bit easier to follow, some of the columns in exibble will first be dropped through a `dplyr::select()` statement. -```{r} -# Create a display table by using `tbl` as input -gt(tbl) +```{r exibble_a} +# Create a gt table using the `exibble` dataset +exibble_a <- + exibble %>% + dplyr::select(-c(fctr, date, time, datetime)) %>% + gt(rowname_col = "row", groupname_col = "group") + +exibble_a ``` -### Generating Summary Rows +There are two groups in this data table: `grp_a` and `grp_b`. This gives us flexibility to create both a grand summary and groupwise summary rows. -Summaries by row group can be generated by using the `summary_rows()` function. There’s a lot of control in how the summaries are conducted and formatted. First of all, we can choose which groups will receive summary rows (the rows appear at the bottom of each row group). This optional choice of groups can be made using the `groups` argument (providing a vector of group names). Secondly, we can choose which columns should be included in the summary with the `columns` argument (in this case, wrapping column names in `vars()`). If we provide nothing to `groups`, then all groups will receive summary data for the selected `columns`. +### Generating Groupwise Summary Rows -To make any sort of summary, we need to use functions that will perform the aggregation. We can provide base functions such as `mean()`, `sum()`, `min()`, `max()`, and more, within a `list()` or `c()`. Each function provided will result in a summary row for each group. +Groupwise summary rows can be generated by using the `summary_rows()` function and, importantly, through specifying the groups that will receive summary rows. We can provide a vector group names, as in `c("grp_a", "grp_b")`, or, use `TRUE` to signify that all groups should receive summary rows. Aside from the selection of groups, there is control over which columns are to used for the summary. Since each call to `summary_rows()` only performs one set of aggregation functions, we may want specific aggregations for different subsets of columns. -Because each function will yield a row, we need to be able to identify that row. So, each summary row will receive a summary row label. We can provide our preferred names by naming the functions within the list or `c()` (e.g, `list(average = "mean", total = "sum", SD = "sd")` or `c("mean", total = "sum", stdev = "sd")`). If names aren't supplied, then **gt** will derive names from the functions supplied and make the names unique. +To make any sort of summary, we need to use functions that will perform the aggregation. We can provide base functions such as `mean()`, `sum()`, `min()`, `max()`, and more, within a `list()`. Each function provided will result in a summary row for each `group`. -Now that the `summary_rows()` function has been somewhat explained, let’s look at how we can get summary rows for the `tbl` table: +Because each function will yield a row, we need to be able to label that row. So, each summary row will receive a summary row label. We can provide our preferred names by naming the functions within the list (e.g, `list(average = "mean", total = "sum", SD = "sd")`). -```{r} -# Create a gt table with summary rows for -# `value_1` in the `A` and `B` row groups; -# three summary rows are made per group -# (one for each function in `fns`) -gt(tbl) %>% +```{r exibble_b} +# Create groupwise summary rows for both +# groups (using `groups = TRUE`); use the +# `mean()`, `sum()`, and `sd()` functions +# (only for the `num` column) +exibble_b <- + exibble_a %>% summary_rows( - groups = c("A", "B"), - columns = vars(value_1), - fns = list("mean", "sum", "sd") + groups = TRUE, + columns = vars(num), + fns = list( + average = "mean", + total = "sum", + SD = "sd") ) + +exibble_b ``` -Here we see that summary rows were created for the `A` and `B` groups (group `C` has no summary lines in its row group). It was specified in `columns` that only the `value_1` column should be evaluated and, indeed, the `value_2` column shows no values whatsoever within the summary rows. +We can specify the aggregation functions by use of function names in quotes (e.g., `"sum"`), as bare functions (e.g., `sum`), or as one-sided R formulas using a leading `~`. In the formula representation, a `.` serves as the data to be summarized, so we can use `sum(., na.rm = TRUE)`. The use of named arguments is recommended as those names will serve as summary row labels (the labels can derived from the function names but only when not providing bare function names). -There is some flexibility in how we supply aggregation functions to `summary_rows()`. It's sometimes sufficient to supply function names enclosed in quotes (e.g., `list("mean", "sum", "sd")`) but the next section will demonstrate a more advanced method for supplying these functions (where we don't have to rely on function defaults). If we already have a vector of function names that use all of the default arguments within those functions, we can pass this directly to `fns`. This is nice if we want to build a common named vector of function names and summary labels. Here's an example that does just that: +Now that the `summary_rows()` function has been somewhat explained, let’s look at how we can create groupwise summary rows for the `exibble_a` table. We'll create summaries for both available groups (`groups = TRUE`) and use the `mean()`, `sum()`, and `sd()` functions with the _function-name-in-quotes_ method (and this will only pertain to the `num` column). -```{r} -# Define a named vector of function names -# and summary row labels -fns_labels <- c(average = "mean", total = "sum", `std dev` = "sd") +In the previous example we have an `NA` value in the `num/row_6` cell, and so we get `NA` outputs from `mean()`, `sum()`, and `sd()` in `grp_b`'s summary rows (which are replaced with em dashes, itself controllable through the `missing_text` option). To avoid this, let's rewrite the above using the _names-and-formulae_ method. -# Use `fns_labels` in `fns` -gt(tbl) %>% +```{r exibble_c} +# Create groupwise summary rows for both +# groups (using `groups = TRUE`); we will +# use names and formulas this time in `fns` +exibble_c <- + exibble_a %>% summary_rows( - columns = vars(value_1), - fns = fns_labels + groups = TRUE, + columns = vars(num), + fns = list( + avg = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + s.d. = ~sd(., na.rm = TRUE) + ) ) -``` -### Providing Calls to Functions with a Formula Interface +exibble_c +``` -Sometimes we want to use functions with some parameters set. The earlier example using `list("mean", "sum", "sd")` will break down if we have `NA` values in our data and we want to exclude those by using `na.rm = TRUE`. In this case we can provide a call to a function with a right-hand side (*RHS*) formula shortcut, having `.` serve as the data values. Here is an example where we modify our `tbl` to include some `NA` values (calling it `tbl_na`) and then changing the contents of the `list()`---using `c()` will work just as well---as calls to functions: +Here we see that summary rows were created for both groups. However, the output of the summary row data is quite different than that of the cell data. The `formatter` argument (and extra `...` arguments) allows for use of any of the `fmt_*()` functions that we'd normally use to format cell data. In this example (another rewrite of the above), the cell data in the `num` column is formatted in scientific notation and the resulting summary cell data is also formatted in the same way (including the options of `decimals = 3`). -```{r} -# Create an alternate version of the -# `tbl` data frame that contains NAs -tbl_na <- - tbl %>% - mutate(value_1 = case_when( - value_1 >= 300 ~ NA_real_, - value_1 < 300 ~ value_1) - ) %>% - mutate(value_2 = case_when( - value_2 >= 600 ~ NA_real_, - value_2 < 600 ~ value_2) +```{r exibble_d} +# Define a named list of aggregation +# functions and summary row labels +fns_labels <- + list( + avg = ~mean(., na.rm = TRUE), + total = ~sum(., na.rm = TRUE), + s.d. = ~sd(., na.rm = TRUE) ) -# Create summary rows from `tbl_na` within -# groups `A` and `B` but provide the -# aggregation functions as formulas so that -# we can modify the default options -gt(tbl_na) %>% +# Create groupwise summary rows as +# before, supply `fns_labels` to `fns`, +# and format the cell summary data +exibble_d <- + exibble_a %>% + fmt_scientific( + columns = vars(num), + decimals = 3 + ) %>% summary_rows( - groups = c("A", "B"), - columns = vars(value_1, value_2), - fns = list( - average = ~mean(., na.rm = TRUE), - sum = ~sum(., na.rm = TRUE), - `std dev` = ~sd(., na.rm = TRUE)) + groups = TRUE, + columns = vars(num), + fns = fns_labels, + formatter = fmt_scientific, + decimals = 3 ) + +exibble_d ``` -The input to `fns` is very permissive in regard to how the functions are defined. It is entirely valid to provide functions in the various forms shown earlier such that `list("sum", ~mean(., na.rm = TRUE), SD = "sd")` will be correctly interpreted. +The input to `fns` is very permissive in regard to how the functions are defined. It is entirely valid to provide functions in the various forms shown earlier such that `list("sum", avg = ~mean(., na.rm = TRUE), SD = "sd")` will be correctly interpreted. It is recommended to use formula notation. -### Formatting the Summary Output Values +The default for `formatter` is set to `fmt_number` which is a sensible default for many scenarios. The setting of argument values for a particular formatter can be done in the `...` area of the function call (as was done above for the `decimals` argument). -Using `summary_rows()` to generate a summary is, in effect, creating new data and thus we need some means to format the new summary row data. We can use the `formatter` option to supply a formatting function to handle the formatting of the summary row data. Thankfully, we have a collection of formatting functions available in the package (i.e., all of the `fmt_*()` functions). The default for `formatter` is set to `fmt_number` which is a sensible default for many scenarios. The setting of argument values for a particular formatter can be done in the `...` area of the function call. +### Using Multiple Calls of `summary_rows()` -Let's start with an example where we format the summary row data using `fmt_number` as the formatter. The `fmt_number()` function several arguments to which we can pass values (`decimals`, `drop_trailing_zeros`, `negative_val`, `locale`, etc.). Here, we will provide `decimals = 3` to augment `fmt_number()`: +We can re-use summary row labels and fill the otherwise empty summary cells with similar aggregations but perhaps with different formatting options. Here's an example where the `currency` column contains aggregrate values that share the same summary rows as for the `num` column, adds two more rows, and uses currency formatting: -```{r} -# Use the formatter options in `...` to -# provide values to `fmt_number` -gt(tbl) %>% +```{r exibble_e} +# Create groupwise summary rows as +# before, supply `fns_labels` to `fns`, +# and format the cell summary data +exibble_e <- + exibble_a %>% + fmt_scientific( + columns = vars(num), + decimals = 3 + ) %>% + fmt_currency( + columns = vars(currency), + currency = "EUR" + ) %>% summary_rows( - groups = "A", - columns = vars(value_1, value_2), - fns = c("mean", "sum", "min", "max"), - formatter = fmt_number, + groups = TRUE, + columns = vars(num), + fns = fns_labels, + formatter = fmt_scientific, decimals = 3 + ) %>% + summary_rows( + groups = "grp_a", + columns = vars(currency), + fns = c( + fns_labels, + min = ~min(.), + max = ~max(.)), + formatter = fmt_currency, + currency = "EUR" ) + +exibble_e ``` -We can also store these argument values as local variables and pass them in both separate `fmt_number()` calls and then to a `summary_rows()` calls with `fmt_number()` used as the formatter. This is useful for standardizing formatting parameters across different table cell types. +A thing to again note in the above example is that even though two independent calls of `summary_rows()` were made, summary data within common summary row names were 'squashed' together, thus avoiding the fragmentation of summary rows. Put another way, we don't create additional summary rows across separate calls if we are referencing the same summary row labels. If the summary row labels provided in `fns` were to be different across columns however, additional summary rows would be produced even if the types of data aggregations were to be functionally equivalent. -```{r} +We can also store these argument values as local variables and pass them in both separate `fmt_*number*()` calls also to arguments within `summary_rows()` calls. This is useful for standardizing formatting parameters across different table cell types. Here's an example of that, which additional passes the `fr_BE` locale to all functions that take a `locale` value. + +```{r exibble_f} # Provide common formatting parameters to a list # object named `formats`; the number of decimal # places will be `2` and the locale is "fr_BE" -formats <- list(decimals = 2, locale = "fr_BE") +formats <- + list( + decimals = 3, + locale = "fr_BE", + currency = "EUR" + ) -# Provide the formatting options from `formats` to -# all row data in all columns, and, to the summary -# row data -gt(tbl) %>% - fmt_number( - columns = vars(value_1, value_2), +# Format the `num` and `currency` columns +# (using the values stored in `formats`); +# when generating summary rows we can also +# supply formatter options from this list +exibble_f <- + exibble_a %>% + fmt_scientific( + columns = vars(num), decimals = formats$decimals, locale = formats$locale ) %>% + fmt_currency( + columns = vars(currency), + currency = formats$currency, + locale = formats$locale + ) %>% summary_rows( - groups = "A", - columns = vars(value_1, value_2), - fns = list("mean", "sum", "min", "max"), - formatter = fmt_number, + groups = TRUE, + columns = vars(num), + fns = fns_labels, + formatter = fmt_scientific, decimals = formats$decimals, locale = formats$locale + ) %>% + summary_rows( + groups = "grp_a", + columns = vars(currency), + fns = c( + fns_labels, + min = ~min(.), + max = ~max(.)), + formatter = fmt_currency, + currency = formats$currency, + locale = formats$locale ) + +exibble_f ``` -### Extracting the Summary Data from the gt Table Object +Passing in parameters like this is useful, especially if there are larger numbers of columns. When we store formatting parameters outside of the `gt()` pipeline, we separate our concerns between data structuring and data formatting. Putting styles and options into objects becomes more important if we intend to centralize formatting options for reuse. -For a reproducible workflow, we do not want to have situations where any data created or modified cannot be accessed. While having summarized values be created in a **gt** pipeline presents advantages to readability and intent of analysis, it is recognized that the output table itself is essentially 'read only', as the input data undergoes processing and movement to an entirely different format. +### Creating a Grand Summary -However, the object created still contains data and we can obtain the summary data from a gt table object using the `extract_summary()` function. Taking the `gt_summary` object, we get a data frame containing the summary data while preserving the correct data types: +A grand summary aggregates column data regardless of the groups within the data. Grand summaries can also be created for **gt** tables that don't have row groups, or, don't have a stub. Finally, we can create a table that has both groupwise summaries and a grand summary. -```{r} -# Create a gt table with summary rows and -# assign it to `gt_object` -gt_object <- - gt(tbl) %>% - summary_rows( - groups = c("A", "B"), - columns = vars(value_1, value_2), - fns = list("mean", "sum", "sd") +Let's keep it simple and create group summary rows on a table without a stub. We'll use `exibble` dataset for this once more. A few `exibble` columns are `select()`ed, passed to `gt()`, and then `summary_rows()`. Notice that, in the resulting table, a stub is created just for the summary row labels (they have to go somewhere). + +```{r exibble_g} +# Create a simple grand summary on a gt +# table that contains no stub +exibble_g <- + exibble %>% + dplyr::select(num, char, currency) %>% + gt() %>% + grand_summary_rows( + columns = vars(num, currency), + fns = fns_labels ) + +exibble_g ``` -```{r} -# Extract the summary data from `gt_object` +By default, `groups` in the `summary_rows()` function is set to `NULL` and will produce a grand summary. + +A grand summary can be used in conjunction with groupwise summaries. Here's an mashup where both types are present: + +```{r exibble_h} +# Using the table in `exibble_f`, create +# additional grand summary rows (using two +# separate calls of `grand_summary_rows()` +# since the formatting +# will be different) +exibble_h <- + exibble_f %>% + grand_summary_rows( + columns = vars(num), + fns = fns_labels, + formatter = fmt_number, + suffixing = TRUE, + locale = formats$locale + ) %>% + grand_summary_rows( + columns = vars(currency), + fns = fns_labels, + formatter = fmt_currency, + suffixing = TRUE, + locale = formats$locale + ) + +exibble_h +``` + +Note that the grand summary has a double line separating it from groupwise summary that's part of `grp_b`. If this default styling appears to be too subtle, we can elect to add further styling to both groupwise summaries and the grand summary by using `tab_options()`. + +### Adding Some Style to the Summary Cells + +While the summary cells (both groupwise and grand) have a distinct appearance that sets them apart from the data cells, there's always the option to modify their appearance. We can use the `tab_options()` function to perform these customizations. Here are the options specific to the summary cells (for groupwise summaries) and the grand summary cells: + +- `summary_row.background.color` & `grand_summary_row.background.color` +- `summary_row.padding` & `grand_summary_row.padding` +- `summary_row.text_transform` & `grand_summary_row.text_transform` + +We can also target the summary cells and grand summary cells with the location helper functions `cells_summary()` and `cells_grand_summary()`. This is important for adding footnotes with `tab_footnote()` and for setting styles with `tab_style()` (both have the `locations` argument). + +Here is an example that uses multiple calls of `tab_options()` and `tab_footnote()`. The cell background color for both types of summary cells is modified and two footnotes are added. + +```{r exibble_i} +# Using the gt table of `exibble_h` as a +# starting point, style summary cells with +# `tab_options()` and add two footnotes +exibble_i <- + exibble_h %>% + tab_options( + summary_row.background.color = "lightblue", + grand_summary_row.background.color = "lightgreen" + ) %>% + tab_footnote( + footnote = md("Mean of all *num* values."), + locations = cells_grand_summary( + columns = vars(num), rows = vars(avg) + ) + ) %>% + tab_footnote( + footnote = md("Highest `currency` value in **grp_a**"), + locations = cells_summary( + groups = "grp_a", + columns = vars(currency), + rows = starts_with("m") + ) + ) + +exibble_i +``` + +### Extracting the Summary Data from the **gt** Table Object + +For a reproducible workflow, we do not want to have situations where any data created or modified cannot be accessed. While having summarized values be created in a **gt** pipeline presents advantages to readability and intent of analysis, it is recognized that the output table itself is essentially 'read only', as the input data undergoes processing and movement to an entirely different format. + +However, the object created still contains data and we can obtain the summary data from a **gt** table object using the `extract_summary()` function. Taking the `gt_summary` object, we get a data frame containing the summary data while preserving the correct data types: + +```{r summary_list} +# Extract the summary data from `exibble_d` # to a data frame object -summary_list <- gt_object %>% extract_summary() +summary_list <- exibble_d %>% extract_summary() # This is a list with two elements named -# `A` and `B` (matches the summary groups) +# `grp_a` and `grp_b` (matches the row +# group labels for those groups that got +# groupwise summaries) names(summary_list) ``` -```{r} -# Print out the summary for the `A` group -summary_list[["A"]] +```{r summary_list_grp_a} +# Print out the summary for the `grp_a` group +summary_list[["grp_a"]] ``` -```{r} -# Print out the summary for the `B` group -summary_list[["B"]] +```{r summary_list_grp_b} +# Print out the summary for the `grp_b` group +summary_list[["grp_b"]] ``` -The output data frames within the list always contain the `groupname` and `rowname` columns. The `groupname` column is filled with the name of the stub group given in `summary_rows()`. The `rowname` column contains the descriptive stub labels for the summary rows (recall that values are either supplied explicitly in `summary_rows()`, or, are generated from the function names). The remaining columns are from the original dataset. +The output tibbles within the list always contain the `groupname` and `rowname` columns. The `groupname` column is filled with the name of the stub group that was given to `summary_rows()`. The `rowname` column contains the descriptive stub labels for the summary rows (recall that values are either supplied explicitly in `summary_rows()`, or, are generated from the function names). The remaining columns are those from the original dataset. -The output data frame from `extract_summary()` can be reintroduced to a reproducible workflow and serve as downstream inputs or undergo validation. Perhaps interestingly, the output data frame is structured in a way that facilitates direct input to `gt()` (i.e., has the magic `groupname` and `rowname` columns). This can produce a new, standalone summary table where the summary rows are now data rows: +The output data from `extract_summary()` can be reintroduced to a reproducible workflow and serve as downstream inputs or undergo validation. Perhaps interestingly, the output tibbles are structured in a way that facilitates direct input back to `gt()` (i.e., it has the magic `groupname` and `rowname` columns). This can produce a new, standalone summary table where the summary rows are now data rows: -```{r} -# Take the `gt_object`, which has a list of -# summary data frames, combine them with -# `do.call(bind_rows, ...)`, input that into -# `gt()`, and format all of the numeric values +```{r exibble_d_summary_list_gt} +# Take `exibble_d`, which internally has a list +# of summary data frames, extract the summaries, +# and then combine them; input that into `gt()`, +# and format the `num` column with `fmt_number()` do.call( dplyr::bind_rows, - gt_object %>% extract_summary() + exibble_d %>% extract_summary() ) %>% gt() %>% fmt_number( - columns = vars(value_1, value_2), - decimals = 3 + columns = vars(num), + decimals = 1 + ) %>% + fmt_missing( + columns = vars(char, currency) ) ``` ### Providing Our Own Aggregation Functions to Generate Summary Rows -While many of the functions available in base R and within packages are useful as aggregate functions, we may occasionally have need to create our own custom functions. The only things to keep in mind are to ensure that a vector of values is the main input, and, a single value is returned. The return value can be most any class (e.g., `numeric`, `character`, `logical`) and it's the `formatter` function that will handle any custom formatting while also converting to `character`. +While many of the functions available in base R and within packages are useful as aggregate functions, we may occasionally have the need to create our own custom functions. When taking this approach the main things to keep in mind are that a vector of values is the main input, and, a single value should be returned. The return value can be pretty much any class (e.g., `numeric`, `character`, `logical`) and it's the `formatter` function that will handle any custom formatting while also converting to `character`. Here, we'll define a function that takes a vector of numeric values and outputs the two highest values (sorted low to high) above a `threshold` value. The output from this function is always a formatted `character` string. -```{r} +```{r define_agg_function} # Define a function that gives the # highest two values above a threshold agg_highest_two_above_value <- function(x, threshold) { @@ -266,107 +410,32 @@ agg_highest_two_above_value( Because this is character value that's returned, we don't need formatting functions like `fmt_number()`, `fmt_percent()`, etc. However, a useful formatter (and we do need *some* formatter) is the `fmt_passthrough()` function. Like the name suggests, it to great extent passes values through but formats as `character` (like all the `fmt_*()` function do) and it provides the option to decorate the output with a `pattern`. Let's have a look at how the `agg_highest_two_above_value()` function can be used with the `fmt_passthrough()` formatter function. -```{r} -# Create a gt table with summary rows for -# `value_1` & `value_2`; the custom function -# is being used with a threshold of `150`; the -# `fmt_passthrough` allows for minimal -# formatting of the aggregate values -summary_tbl <- - gt(tbl_na) %>% - summary_rows( - columns = vars(value_1, value_2), +```{r exibble_j} +# Create a gt table with `exibble_a` and use +# the custom function with a threshold of `20`; +# the `fmt_passthrough` funtion allows for +# minimal formatting of the aggregate values +exibble_j <- + exibble_a %>% + gt() %>% + grand_summary_rows( + columns = vars(num, currency), fns = list( - high = ~agg_highest_two_above_value(., 150)), + high = ~agg_highest_two_above_value(., 20)), formatter = fmt_passthrough, pattern = "({x})" - ) %>% - fmt_missing(columns = vars(value_1, value_2)) + ) -summary_tbl +exibble_j ``` -We can extract the summary data from the `summary_tbl` object. Note that columns `value_1` and `value_2` are classed as character since it was character outputs that were generated by the `agg_highest_two_above_value()` function. +We can extract the grand summary data from the `exibble_j` object. Note that columns `num` and `currency` are classed as character since it was character outputs that were generated by the `agg_highest_two_above_value()` function. ```{r} -summary_tbl %>% +# Extract the summary list from `exibble_j` +# and inspect using `str()` +exibble_j %>% extract_summary() %>% str() ``` -### Using Different Formatters for Different Columns - -Suppose we have data across columns that should be summarized in the same way (i.e., common aggregate functions) but formatted differently (e.g., decimal notation, scientific notation, percentages, etc.). For each type of formatting, we need to call `summary_rows()`, however, we can employ certain strategies to make the code a bit more succinct while doing so. - -Let's start with a new data table. This table contains `groupname` and `rowname` columns, which making using `summary_rows()` possible, along with `large`, `medium`, and `small` data columns, all containing numeric values. - -```{r} -tbl_2 <- - dplyr::tribble( - ~groupname, ~rowname, ~large, ~medium, ~small, - "A", "1", 235342.6, 342.2, 0.34, - "A", "2", 184123.0, 971.7, 0.23, - "A", "3", 342622.3, 392.6, 0.73, - "A", "4", 234353.9, 684.5, 0.93, - "B", "1", 190983.4, 328.0, 0.35, - "B", "2", 748250.3, 671.3, 0.98, - "B", "3", 252781.3, 934.2, 0.74, - "B", "4", 344030.7, 673.3, 0.27, - ) - -tbl_2 -``` - -Here, we would like to apply a different format (both to the data rows and to the summary rows) across the three columns. We can store formatting options to three different list objects (`large_fmts`, `medium_fmts`, and `small_fmts`) and use the stored values in the **gt** pipeline. - -```{r} -# Store formatting options in list objects -large_fmts <- - list( - columns = "large", - formatter = fmt_scientific, - options = list(decimals = 2) - ) - -medium_fmts <- - list( - columns = "medium", - formatter = fmt_number, - options = list(decimals = 2) - ) - -small_fmts <- - list( - columns = "small", - formatter = fmt_percent, - options = list(decimals = 5) - ) - -# Format the data rows, then, create summary rows -# and format summary data for consistent output in -# each column -tbl_2 %>% - gt() %>% - fmt_scientific(columns = large_fmts$columns) %>% - fmt_number(columns = medium_fmts$columns) %>% - fmt_percent(columns = small_fmts$columns) %>% - summary_rows( - columns = large_fmts$columns, - fns = c("sum", "mean", "sd"), - formatter = large_fmts$formatter - ) %>% - summary_rows( - columns = medium_fmts$columns, - fns = c("sum", "mean", "sd"), - formatter = medium_fmts$formatter - ) %>% - summary_rows( - columns = small_fmts$columns, - fns = c("sum", "mean", "sd"), - formatter = small_fmts$formatter - ) -``` - -Passing in parameters like this is useful, especially if there are larger numbers of columns. Additionally, we can store formatting parameters outside of the `gt()` pipeline and separate our concerns between data structuring and data formatting. The separation of styles and options into objects becomes more important if we intend to centralize formatting options for reuse. - -Another thing to note in the above example is that even though multiple independent calls of `summary_rows()` were made, summary data within common summary row names were 'squashed' together, thus avoiding the fragmentation of summary rows. Put another way, we don't create additional summary rows from a group across separate calls if we are referencing the same summary row labels. If the summary row labels provided in `fns` were to be different across columns, however, additional summary rows would be produced even if the types of data aggregations were to be functionally equivalent. From d0c64c792f39236f92d85c41a0d5394bca32ef08 Mon Sep 17 00:00:00 2001 From: Richard Iannone Date: Fri, 26 Apr 2019 21:37:46 -0400 Subject: [PATCH 8/8] Use webshot to generate images of HTML tables (#257) * Add the `gt_save_webshot()` function * Modify roxygen documentation * Modify switch statement * Modify stop message * Modify roxygen documentation * Update help file using roxygen * Modify `stop()` message * Use the `gt_save_html()` fn with default options * Remove jpeg options from `gtsave()` * Add linebreaks to function signatures * Add `zoom` and `expand` arguments to `gt_save_webshot()` * Reverse slashes on Windows filesystems * Add extra slash for file URI * Modify the call to `webshot()` * Modify roxygen documentation * Refactor `switch()` statement * Refactor conditional statement * Modify `stop()` message * Update help file using roxygen * Pass `...` to saving methods --- R/gtsave.R | 96 +++++++++++++++++++++++++++++++++++++++++---------- man/gtsave.Rd | 12 ++++--- 2 files changed, 86 insertions(+), 22 deletions(-) diff --git a/R/gtsave.R b/R/gtsave.R index 2b065ab877..4029848c6e 100644 --- a/R/gtsave.R +++ b/R/gtsave.R @@ -2,7 +2,7 @@ #' #' The `gtsave()` function makes it easy to save a \pkg{gt} table to a file. The #' function guesses the file type by the extension provided in the output -#' filename, producing either an HTML, LaTeX, or RTF file. +#' filename, producing either an HTML, LaTeX, RTF, PNG, or PDF file. #' #' Output filenames with either the `.html` or `.htm` extensions will produce an #' HTML document. In this case, we can pass a `TRUE` or `FALSE` value to the @@ -10,10 +10,14 @@ #' default is `FALSE`). More details on CSS inlining are available at #' [as_raw_html()]. #' -#' If the output filename is either of `.tex`, `.ltx`, or `.rnw`, a LaTeX -#' document is produced. An output filename of `.rtf` will generate an RTF +#' If the output filename extension is either of `.tex`, `.ltx`, or `.rnw`, a +#' LaTeX document is produced. An output filename of `.rtf` will generate an RTF #' document. The LaTeX and RTF saving function don't have any options to pass to -#' `...`. +#' the triple-dots. +#' +#' We can create an image file based on the HTML version of the `gt` table. With +#' the filename extension `.png`, we get a PNG image file. A PDF document can be +#' generated by using the `.pdf` extension. #' #' @param data A table object that is created using the [gt()] function. #' @param filename The file name to create on disk. Ensure that an extension @@ -23,7 +27,9 @@ #' @param ... All other options passed to the appropriate internal saving #' function. #' @export -gtsave <- function(data, filename, ...) { +gtsave <- function(data, + filename, + ...) { # Input object validation stop_if_not_gt(data) @@ -34,20 +40,26 @@ gtsave <- function(data, filename, ...) { # Stop function if a file extension is not provided if (file_ext == "") { - stop("A file extension is required in the provided filename.\n", - " * We can use `", filename, "` + either of `.html`/`.htm`, `.tex`/`.ltx`/`.rnw`, or `.rtf`", + stop("A file extension is required in the provided filename. We can use:\n", + " * `.html`/`.htm` (HTML file)\n", + " * `.tex`/`.ltx`/`.rnw` (LaTeX file)\n", + " * `.rtf` (RTF file)\n", + " * `.png` (PNG file)\n", + " * `.pdf` (PDF file)", call. = FALSE) } # Use the appropriate save function based # on the filename extension switch(file_ext, - htm = gt_save_html(data, filename, ...), + htm = , html = gt_save_html(data, filename, ...), - ltx = gt_save_latex(data, filename, ...), - rnw = gt_save_latex(data, filename, ...), - tex = gt_save_latex(data, filename, ...), - rtf = gt_save_rtf(data, filename, ...), + ltx = , + rnw = , + tex = gt_save_latex(data, filename, ...), + rtf = gt_save_rtf(data, filename, ...), + png = , + pdf = gt_save_webshot(data, filename, ...), { stop("The file extension used (`.", file_ext, "`) doesn't have an ", "associated saving function.\n", @@ -61,27 +73,73 @@ gtsave <- function(data, filename, ...) { #' #' @importFrom htmltools as.tags save_html HTML #' @noRd -gt_save_html <- function(data, filename, ..., inline_css = FALSE) { +gt_save_html <- function(data, + filename, + ..., + inline_css = FALSE) { if (inline_css) { data %>% as_raw_html(inline_css = inline_css) %>% htmltools::HTML() %>% - htmltools::save_html(filename) + htmltools::save_html(filename, ...) } else { data %>% htmltools::as.tags() %>% - htmltools::save_html(filename) + htmltools::save_html(filename, ...) + } +} + +#' Saving function for an image file via the webshot package +#' +#' @noRd +gt_save_webshot <- function(data, + filename, + ..., + zoom = 2, + expand = 5) { + + # Create a temporary file with the `html` extension + tempfile_ <- tempfile(fileext = ".html") + + # Reverse slashes on Windows filesystems + tempfile_ <- + tempfile_ %>% + tidy_gsub("\\\\", "/") + + # Save gt table as HTML using the `gt_save_html()` function + data %>% gt_save_html(filename = tempfile_) + + # Saving an image requires the webshot package; if it's + # not present, stop with a message + if (!requireNamespace("webshot", quietly = TRUE)) { + + stop("The `webshot` package is required for saving images of gt tables.", + call. = FALSE) + + } else { + + # Save the image in the working directory + webshot::webshot( + url = paste0("file:///", tempfile_), + file = filename, + selector = "table", + zoom = zoom, + expand = expand, + ... + ) } } #' Saving function for a LaTeX file #' #' @noRd -gt_save_latex <- function(data, filename, ...) { +gt_save_latex <- function(data, + filename, + ...) { data %>% as_latex() %>% @@ -91,14 +149,16 @@ gt_save_latex <- function(data, filename, ...) { #' Saving function for an RTF file #' #' @noRd -gt_save_rtf <- function(data, filename, ...) { +gt_save_rtf <- function(data, + filename, + ...) { data %>% as_rtf() %>% writeLines(con = filename) } -#' Get the file extension from an input filename +#' Get the lowercase extension from a filename #' #' @importFrom tools file_ext #' @noRd diff --git a/man/gtsave.Rd b/man/gtsave.Rd index 588d69d9ad..b22672c97f 100644 --- a/man/gtsave.Rd +++ b/man/gtsave.Rd @@ -20,7 +20,7 @@ function.} \description{ The \code{gtsave()} function makes it easy to save a \pkg{gt} table to a file. The function guesses the file type by the extension provided in the output -filename, producing either an HTML, LaTeX, or RTF file. +filename, producing either an HTML, LaTeX, RTF, PNG, or PDF file. } \details{ Output filenames with either the \code{.html} or \code{.htm} extensions will produce an @@ -29,8 +29,12 @@ HTML document. In this case, we can pass a \code{TRUE} or \code{FALSE} value to default is \code{FALSE}). More details on CSS inlining are available at \code{\link[=as_raw_html]{as_raw_html()}}. -If the output filename is either of \code{.tex}, \code{.ltx}, or \code{.rnw}, a LaTeX -document is produced. An output filename of \code{.rtf} will generate an RTF +If the output filename extension is either of \code{.tex}, \code{.ltx}, or \code{.rnw}, a +LaTeX document is produced. An output filename of \code{.rtf} will generate an RTF document. The LaTeX and RTF saving function don't have any options to pass to -\code{...}. +the triple-dots. + +We can create an image file based on the HTML version of the \code{gt} table. With +the filename extension \code{.png}, we get a PNG image file. A PDF document can be +generated by using the \code{.pdf} extension. }