Package {tsg}


Type: Package
Title: Generate Publication-Ready Statistical Tables
Version: 0.2.0
Description: A table and summary generator: a collection of functions for generating frequency tables and cross-tabulations of categorical variables. The resulting tables can be exported to various formats (Excel, PDF, HTML, etc.) with extensive formatting and layout customization options.
Author: Bhas Abdulsamad ORCID iD [aut, cre, cph]
Maintainer: Bhas Abdulsamad <aeabdulsamad@gmail.com>
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
Imports: haven, openxlsx, fs, forcats, purrr, tidyr, glue, jsonlite (≥ 2.0.0), yaml (≥ 2.3.10), dplyr (≥ 1.1.0), stringr (≥ 1.4.0), rlang (≥ 1.0.2), lifecycle, stats, utils
Suggests: testthat (≥ 3.0.0), cli, devtools, knitr, rmarkdown, tibble, webshot2, withr, DBI, dbplyr, RSQLite, googledrive, gargle, gt, officer, flextable, qpdf, chromote
Config/testthat/edition: 3
Depends: R (≥ 4.1.0)
VignetteBuilder: knitr
URL: https://yng-me.github.io/tsg/, https://github.com/yng-me/tsg
BugReports: https://github.com/yng-me/tsg/issues
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-20 07:11:22 UTC; bhasabdulsamad
Repository: CRAN
Date/Publication: 2026-11-20 07:40:02 UTC

tsg: Generate Publication-Ready Statistical Tables

Description

A table and summary generator: a collection of functions for generating frequency tables and cross-tabulations of categorical variables. The resulting tables can be exported to various formats (Excel, PDF, HTML, etc.) with extensive formatting and layout customization options.

Author(s)

Maintainer: Bhas Abdulsamad aeabdulsamad@gmail.com (ORCID) [copyright holder]

Authors:

See Also

Useful links:


Add a column total

Description

Add a column total

Usage

add_column_total(data, name = "total", label_total = "Total", ...)

Arguments

data

A data frame, tibble, or tsg object to which a column row will be added.

name

Column name for total. Default value is "total".

label_total

Label for the total column. Default is "Total".

...

Additional named arguments to be added as columns alongside the total column.

Value

The input data frame with an additional column representing the total of each row.

Examples

# Example data frame
df <- data.frame(
 category = c("A", "B", "C"),
 value1 = c(10, 20, 30),
 value2 = c(5, 15, 25)
 )
add_column_total(df)


Add a facade to a tsg table

Description

This function adds a facade to a tsg table object. A facade is a set of styling options that can be applied to the table to customize its appearance. For Excel output, see openxlsx::createStyle() for all valid values.

Usage

add_facade(data, ...)

Arguments

data

A tsg table object to which the facade will be added. This is typically a data frame or tibble that has been processed using tsg functions.

...

Facade settings as part.property = value pairs, e.g. header.fontSize = 12. Valid keys are those of the default facade (see Details); an unknown key is an error. NULL values are ignored (they do not turn a setting off; use a facade file for that).

Details

Keys are part.property. The parts are table, title, subtitle, header, spanner (upper rows of a multi-level header), body, col_first, col_last, row_group, sub_group, source_note, footnotes, border_header, border_outer, border_bottom and label.

Style properties follow openxlsx::createStyle(): fontName, fontSize, fontColour, numFmt, border, borderColour, borderStyle, bgFill, fgFill, halign, valign, textDecoration, wrapText and indent. fgFill is the fill colour of a cell; bgFill is the background of an Excel fill pattern and shows only behind one (HTML and Word use it when fgFill is unset). Colours are hexadecimal codes (e.g. "#FF0000") or colour names. border is any of "top", "bottom", "left" and "right"; borderStyle uses the Excel names ("thin", "medium", "thick", "dashed", "dotted", "double", "hair", "mediumDashed", "dashDot", ...) in every output format; HTML, PDF and Word translate them to their nearest line.

The same keys style every output format. Settings that only mean something in a spreadsheet (height, width, table.offsetRow, table.offsetCol, table.gridLines, table.tabColour, table.locked, table.hidden, table.widthOffset, indent, wrapText) are ignored by HTML, PDF and Word.

Layout properties:

In a facade file (or a facade list passed to a writer), a key set to ~ (NULL) turns that setting off instead of falling back to the default. In add_facade() a NULL value is ignored, so it cannot turn a setting off for one table.

Use generate_template(path, "facade") to get a YAML file listing every key with its default.

Value

A tsg object with the specified facade settings applied as attributes.

Examples

person_record |>
 generate_frequency(sex) |>
 add_facade(table.offsetRow = 2, table.offsetCol = 1)

Add a facade to a tsg table (alternative way)

Description

[Deprecated]

add_facade() now evaluates its arguments, so this alternative is no longer needed.

Usage

add_facade_alt(data, ...)

Arguments

data

a tsg data frame

...

List of supported facade items (see add_facade())

Value

A tsg object with the specified facade settings applied as attributes.

Examples

person_record |>
 generate_frequency(sex) |>
 add_facade_alt(table.offsetRow = 2, table.offsetCol = 1)

Add a footnote attribute to a table

Description

Add a footnote attribute to a table

Usage

add_footnote(
  data,
  footnote,
  locations = NULL,
  placement = c("auto", "right", "left")
)

Arguments

data

A data frame, tibble, or tsg object to which a footnote attribute will be added.

footnote

The footnote text to be added (a single character string).

locations

Optional character vector of column names to anchor the footnote marker. When supplied, a footnote reference symbol is placed in those column headers. Column-level anchoring is supported in HTML and PDF output (via gt); XLSX and Word output include the text without cell-level markers. Default NULL renders the footnote as a table-level footer with no marker.

placement

Horizontal alignment of the footnote in the output footer. One of "auto" (default, equivalent to "left"), "right", or "left". Respected by all three output formats (HTML/PDF, XLSX, Word).

Value

The input data frame with an updated footnotes attribute (a list with elements $text, $placement, and $locations).

Examples

tbl <- person_record |> generate_frequency(sex)

# Whole-table footer, left-aligned (default)
tbl |> add_footnote("Source: National Survey 2023.")

# Right-aligned footer note
tbl |> add_footnote("Weighted estimates.", placement = "right")

# Footnote anchored to a specific column header (HTML/PDF)
tbl |> add_footnote("Unweighted count.", locations = "frequency")

Add a row total

Description

Add a row total

Usage

add_row_total(
  data,
  position = c("bottom", "top"),
  label_total = "Total",
  fill = "-"
)

Arguments

data

A data frame, tibble, or tsg object to which a total row will be added.

position

Position to add the total row. Either "bottom" (default) or "top".

label_total

Label for the total row in the category column. Default is "Total".

fill

Character. Value to fill in for missing numeric columns in the total row. Default is "-".

Value

The input data frame with an additional row representing the total of numeric columns.

Examples

# Example data frame
df <- data.frame(
 category = c("A", "B", "C"),
 value1 = c(10, 20, 30),
 value2 = c(5, 15, 25)
)

df_with_total <- add_row_total(df)
df_with_total_top <- add_row_total(df, position = "top")


Add a source note attribute to a table

Description

Add a source note attribute to a table

Usage

add_source_note(data, source_note)

Arguments

data

A data frame, tibble, or tsg object to which a source note attribute will be added.

source_note

The source note text to be added.

Value

The input data frame with an added source note attribute.

Examples

add_source_note(
  dplyr::starwars,
  source_note = "Source: Star Wars API (SWAPI)."
)

Add a subtitle attribute to a table

Description

Add a subtitle attribute to a table

Usage

add_table_subtitle(data, subtitle)

Arguments

data

A data frame, tibble, or tsg object to which a subtitle attribute will be added.

subtitle

The subtitle text to be added.

Value

The input data frame with an added subtitle attribute.

Examples

add_table_subtitle(
  dplyr::starwars,
  subtitle = "Star Wars Character Data"
)


Add a title attribute to a table

Description

Add a title attribute to a table

Usage

add_table_title(data, title)

Arguments

data

A data frame, tibble, or tsg object to which a title attribute will be added.

title

The title text to be added.

Value

The input data frame with an added title attribute.

Examples

add_table_title(
  dplyr::starwars,
  title = "Star Wars Character Data"
)

Convert a tsg table to a gt table

Description

Builds the gt table that write_html() and write_pdf() save, styled with a facade, so you can show it in a Quarto or R Markdown document, a Shiny app, or style it further with gt.

Usage

as_gt(
  data,
  title = NULL,
  subtitle = NULL,
  source_note = NULL,
  footnotes = NULL,
  names_separator = "__",
  facade = get_tsg_facade(which = "html")
)

Arguments

data

A tsg table or a data frame.

title

Optional title; defaults to the table's title (see add_table_title()).

subtitle

Optional subtitle; defaults to the table's subtitle.

source_note

Optional source note; defaults to the table's source note.

footnotes

Optional character vector of footnotes; defaults to the table's footnotes.

names_separator

Column name separator for spanners. Default "__".

facade

A built-in facade name (e.g. "booktabs"; see get_tsg_facade()), the path to a .yaml or .json facade file, or a facade list. Keys missing from it fall back to the html default facade; settings added with add_facade() take precedence over it.

Value

A gt_tbl object.

Examples


person_record |>
  generate_crosstab(marital_status, sex) |>
  add_table_title("Marital status by sex") |>
  as_gt(facade = "booktabs")


Collapse a list of data frames or tibbles into a single data frame

Description

Collapse a list of data frames or tibbles into a single data frame

Usage

collapse_list(
  data,
  ...,
  col_id = "category",
  label = NULL,
  pluck = NULL,
  as_proportion = FALSE,
  name_separator = "_",
  label_separator = "__"
)

Arguments

data

A list of data frames or tibbles to be collapsed.

...

Additional arguments passed to dplyr::filter().

col_id

The name of the column to be created for the category.

label

A label for the category column. If NULL, defaults to "Category".

pluck

A character vector of column names to pluck from the data frames. If NULL, all columns are retained.

as_proportion

If TRUE, the frequency values will be converted to proportions. Default is FALSE.

name_separator

A string to separate the names of the columns in the output data frame. Default is "_".

label_separator

A string to separate the labels of the columns in the output data frame. Default is "__".

Value

A data frame with the specified category column and the frequency and percent columns for each category, along with any additional columns specified in pluck.

Examples

person_record |>
  generate_frequency(
    seeing,
    hearing,
    walking,
    remembering,
    self_caring,
    communicating
  ) |>
  collapse_list()

Convert labelled factors to regular factors

Description

Convert labelled factors to regular factors

Usage

convert_factor(data)

Arguments

data

A data frame, tibble, or tsg object containing labelled factors.

Value

A data frame with labelled factors converted to regular factors.

Examples

df <- data.frame(
  category = haven::labelled(
    c(1, 2, 3),
    c("One" = 1, "Two" = 2, "Three" = 3)
   )
 )

df_converted <- convert_factor(df)

Generate cross-tabulation

Description

Generate cross-tabulation

Usage

generate_crosstab(
  data,
  x,
  ...,
  add_total = TRUE,
  add_total_row = TRUE,
  add_total_column = TRUE,
  add_percent = TRUE,
  as_proportion = FALSE,
  percent_by_column = FALSE,
  name_separator = "_",
  label_separator = "__",
  label_total = "Total",
  label_total_column = NULL,
  label_total_row = NULL,
  label_na = "Not reported",
  label_as_group_name = TRUE,
  label_group_hierarchy = "All",
  include_na = TRUE,
  recode_na = "auto",
  group_separator = " - ",
  group_as_list = FALSE,
  group_as_hierarchy = FALSE,
  calculate_per_group = TRUE,
  expand_categories = TRUE,
  position_total = "bottom",
  sort_column_names = TRUE,
  collapse_list = FALSE,
  convert_factor = FALSE,
  multiple_columns = FALSE,
  multiple_columns_type = c("filtered", "stacked"),
  multiple_columns_filter = 1L,
  metadata = NULL
)

Arguments

data

A data frame (typically tibble) containing the variables to summarize.

x

The variable to use for the rows of the cross-tabulation.

...

Additional variable(s) to use for the columns of the cross-tabulation. If none are provided, a frequency table for x will be returned.

add_total

Logical. If TRUE, adds total row and/or column.

add_total_row

Logical. If TRUE, adds a total row.

add_total_column

Logical. If TRUE, adds a total column.

add_percent

Logical. If TRUE, adds percent or proportion values to the table.

as_proportion

Logical. If TRUE, displays proportions instead of percentages (range 0 to 1).

percent_by_column

Logical. If TRUE, percentages are calculated by column; otherwise, by row.

name_separator

Character. Separator used when constructing variable names in the output.

label_separator

Character. Separator used when constructing labels in the output.

label_total

Character. Label used for the total row/category.

label_total_column

Character. Label used for the total column/category.

label_total_row

Character. Label used for the total row/category.

label_na

Character. Label to use for missing (NA) values.

label_as_group_name

Logical. If TRUE, uses the variable label of the grouping variable(s) as the name in the output list.

label_group_hierarchy

Character. Label applied to grand-total entries when group_as_hierarchy = TRUE. Can be a single string (applied to all group levels) or a named character vector keyed by group column name for per-variable labels (e.g. c(sex = "All sexes", employed = "All workers")). Defaults to "All".

include_na

Logical. If TRUE, includes missing values in the cross table.

recode_na

Character or NULL. Value used to replace missing values in labelled vectors; "auto" will determine a code automatically.

group_separator

Character. Separator used when concatenating group values in list output (if group_as_list = TRUE with a single group).

group_as_list

Logical. If TRUE, output is a named list of cross-tabulation tables keyed by group value. With a single group the list is flat; with 2+ groups the list is nested. When combined with group_as_hierarchy = TRUE, a nested list with totals at each level is returned.

group_as_hierarchy

Logical. When TRUE (without group_as_list), inserts grand-total rows into the output. When TRUE together with group_as_list = TRUE, returns a nested named list with a total entry at each level; the total key is formatted as "{var_label}: {label_group_hierarchy}".

calculate_per_group

Logical. If TRUE, calculates the cross-tabulation separately for each group defined by the grouping variable(s).

expand_categories

Logical. If TRUE, ensures that all categories of x are represented in the output, even if they have zero counts.

position_total

Character. Position of the total row/column; either "bottom" or "top" for rows, and "right" or "left" for columns.

sort_column_names

Logical. If TRUE, sorts the column names in the output.

collapse_list

Logical. If TRUE and several column variables are given in ..., combines their cross-tabulations side by side into one table, with each variable's columns under a spanner header. Ignored when group_as_list = TRUE.

convert_factor

Logical. If TRUE, converts labelled variables to factors in the output. See also convert_factor().

multiple_columns

[Experimental] Logical or NULL. If TRUE, each column in ... is treated as a binary indicator variable. Rows where the column equals multiple_columns_filter are counted per x category and presented as side-by-side frequency/percent columns in a single wide table. Requires at least 2 columns in ...; if fewer are supplied a warning is issued and the function falls back to regular cross-tabulation mode.

multiple_columns_type

Character. Controls how multiple_columns = TRUE handles the additional columns. "filtered" (default) treats each column as a binary indicator and produces a wide table with one column-pair per variable. "stacked" stacks results hierarchically: each column in ... becomes a row group with x categories as columns; multiple_columns_filter is ignored in this mode.

multiple_columns_filter

Scalar value (default 1L). The value to filter on when multiple_columns = TRUE and multiple_columns_type = "filtered". Ignored when multiple_columns_type = "stacked".

metadata

A named list with optional metadata to attach as attributes, e.g. title, subtitle, and source_note.

Value

A data frame or a list of data frames containing the cross-tabulation results. If group_as_list is TRUE, the output will be a list of data frames, one for each combination of grouping variable(s). Otherwise, a single data frame is returned. Each data frame includes counts and, if specified, percentages or proportions for each combination of x and the additional variables provided in ....

See Also

generate_frequency(), generate_output(), rename_label(), remove_label()

Examples

# Using built-in dataset `person_record`

# Basic usage
person_record |>
 generate_crosstab(marital_status, sex)


# Multiple variables
person_record |>
 generate_crosstab(
  sex,
  seeing,
  hearing,
  walking,
  remembering,
  self_caring,
  communicating
 )

 # Grouping
 person_record |>
   dplyr::group_by(sex) |>
   generate_crosstab(marital_status, employed, group_as_list = TRUE)

 # Nested list with totals at each level (group_as_list + group_as_hierarchy)
 person_record |>
   dplyr::group_by(sex) |>
   generate_crosstab(marital_status, employed,
     group_as_list = TRUE, group_as_hierarchy = TRUE)

# # Percent or proportion by row or column
person_record |>
 generate_crosstab(
   marital_status,
   sex,
   percent_by_column = TRUE
 )

Generate frequency table

Description

Creates frequency tables for one or more categorical variables, optionally grouped by other variables. The function supports various enhancements such as sorting, totals, percentages, cumulative statistics, handling of missing values, and label customization. It returns a single table or a list of frequency tables.

Usage

generate_frequency(
  data,
  ...,
  sort_value = TRUE,
  sort_desc = TRUE,
  sort_except = NULL,
  add_total = TRUE,
  add_percent = TRUE,
  add_cumulative = FALSE,
  add_cumulative_percent = FALSE,
  as_proportion = FALSE,
  include_na = TRUE,
  recode_na = "auto",
  position_total = c("bottom", "top"),
  calculate_per_group = TRUE,
  group_separator = " - ",
  group_as_list = FALSE,
  group_as_hierarchy = FALSE,
  label_group_hierarchy = "All",
  label_as_group_name = TRUE,
  label_stub = NULL,
  label_na = "Not reported",
  label_total = "Total",
  expand_categories = TRUE,
  convert_factor = FALSE,
  collapse_list = FALSE,
  top_n = NULL,
  top_n_only = FALSE,
  metadata = NULL
)

Arguments

data

A data frame (typically tibble) containing the variables to summarize.

...

One or more unquoted variable names (passed via tidy evaluation) for which to compute frequency tables.

sort_value

Logical. If TRUE, frequency values will be sorted.

sort_desc

Logical. If TRUE, sorts in descending order of frequency. If sort_value = FALSE, the category is sorted in ascending order.

sort_except

Optional character vector. Variables to exclude from sorting.

add_total

Logical. If TRUE, adds a total row or value to the frequency table.

add_percent

Logical. If TRUE, adds percent or proportion values to the table.

add_cumulative

Logical. If TRUE, adds cumulative frequency counts.

add_cumulative_percent

Logical. If TRUE, adds cumulative percentages (or proportions if as_proportion = TRUE).

as_proportion

Logical. If TRUE, displays proportions instead of percentages (range 0 to 1).

include_na

Logical. If TRUE, includes missing values in the frequency table.

recode_na

Character or NULL. Value used to replace missing values in labelled vectors; "auto" will determine a code automatically.

position_total

Character. Where to place the total row: "top" or "bottom".

calculate_per_group

Logical. If TRUE, calculates frequencies within groups defined in data (from group_by() or existing grouping).

group_separator

Character. Separator used when concatenating group values in list output (if group_as_list = TRUE with a single group).

group_as_list

Logical. If TRUE, output is a named list of frequency tables keyed by group value. With a single group the list is flat; with 2+ groups the list is nested. When combined with group_as_hierarchy = TRUE, a nested list with totals at each level is returned.

group_as_hierarchy

Logical. When TRUE (without group_as_list), inserts grand-total rows into the output. When TRUE together with group_as_list = TRUE, returns a nested named list with a total entry at each level; the total key is formatted as "{var_label}: {label_group_hierarchy}".

label_group_hierarchy

Character. Label applied to grand-total entries when group_as_hierarchy = TRUE. Can be a single string (applied to all group levels) or a named character vector keyed by group column name for per-variable labels (e.g. c(sex = "All sexes", employed = "All workers")). Defaults to "All".

label_as_group_name

Logical. If TRUE, uses variable labels as names in the output list; otherwise, uses variable names.

label_stub

Optional character vector used for labeling output tables (e.g., for export or display).

label_na

Character. Label to use for missing (NA) values.

label_total

Character. Label used for the total row/category.

expand_categories

Logical. If TRUE, ensures all categories (including those with zero counts) are included in the output.

convert_factor

Logical. If TRUE, converts labelled variables to factors in the output. See also convert_factor().

collapse_list

Logical. If TRUE and group_as_list = TRUE, collapses the list of frequency tables into a single data frame with group identifiers. See also collapse_list().

top_n

Integer or NULL. If specified, limits the output to the top n categories by frequency.

top_n_only

Logical. If TRUE and top_n is specified, only the top n categories are included, excluding others.

metadata

A named list with optional metadata to attach as attributes, e.g. title, subtitle, and source_note.

Value

A frequency table (tibble, possibly nested) or a list of such tables. Additional attributes such as labels, metadata, and grouping information may be attached. The returned object is of class "tsg".

See Also

generate_crosstab(), generate_output(), rename_label(), remove_label()

Examples

# Using built-in dataset `person_record`


# Basic usage
person_record |>
 generate_frequency(sex)

# Multiple variables
person_record |>
  generate_frequency(sex, age, marital_status)

# Grouping
person_record |>
  dplyr::group_by(sex) |>
  generate_frequency(marital_status)

# Output group as list
person_record |>
  dplyr::group_by(sex) |>
  generate_frequency(marital_status, group_as_list = TRUE)

# Nested list with totals at each level (group_as_list + group_as_hierarchy)
person_record |>
  dplyr::group_by(sex) |>
  generate_frequency(marital_status, group_as_list = TRUE, group_as_hierarchy = TRUE)

# Sorting

# default is TRUE
person_record |>
  generate_frequency(age, sort_value = TRUE)

# If FALSE, the output will be sorted by the variable values in ascending order.
person_record |>
  generate_frequency(age, sort_value = FALSE)

# See vignettes for more examples.

Generate output in specified format (e.g., xlsx, html, pdf, word)

Description

Generate output in specified format (e.g., xlsx, html, pdf, word)

Usage

generate_output(
  data,
  path,
  ...,
  format = c("xlsx", "gsheet", "html", "pdf", "word")
)

Arguments

data

Preferably a tsg class object for best results. A data frame, tibble, and list are also supported.

path

File path to save the output. For HTML/PDF with a list and separate_files = TRUE (HTML) or any list (PDF), this is treated as a directory path. For "gsheet", a Google Sheet name or an existing sheet; see write_gsheet().

...

Additional arguments passed to specific format functions:

  • "xlsx": passed to write_xlsx

  • "gsheet": passed to write_gsheet (requires the googledrive package)

  • "html": passed to write_html (requires the gt package)

  • "pdf": passed to write_pdf (requires the gt and webshot2 packages)

  • "word": passed to write_docx (requires the officer and flextable packages)

format

Output format. One of "xlsx", "gsheet" (Google Sheets), "html", "pdf", or "word".

Value

Invisibly returns NULL. Called for its side-effect of writing output file(s).

Examples

# Generate an xlsx file from a tsg object
data <- generate_frequency(dplyr::starwars, sex)

dir_to <- tempdir()
generate_output(
  data,
  file.path(dir_to, "starwars_frequency.xlsx"),
  format = "xlsx"
)

unlink(file.path(dir_to, "starwars_frequency.xlsx"))


Generate a summary table of numeric variables

Description

Generate a summary table of numeric variables

Usage

generate_summary(
  data,
  ...,
  stats = c("n", "mean", "sd", "median", "min", "max"),
  group_as_list = FALSE,
  group_separator = " - ",
  metadata = NULL
)

Arguments

data

A data frame (typically tibble), or a lazy table (e.g. dplyr::tbl() on a database connection), in which case the statistics are computed in the database. Group it with dplyr::group_by() to summarise per group.

...

Numeric variables to summarise (tidyselect). If none are given, every numeric column without value labels is used.

stats

Statistics to compute, any of "n", "n_missing", "mean", "sd", "median", "min", "max", "p25" and "p75". A database that cannot compute one (e.g. SQLite has no quantile() for "p25") gives an error naming it.

group_as_list

Logical. If TRUE, returns a list with one table per group.

group_separator

Character. Separator between group values in list names.

metadata

A named list with optional metadata to attach as attributes, e.g. title, subtitle, and source_note.

Value

A table of class "tsg" with one row per variable (its label in category) and one column per statistic, or a list of such tables when group_as_list = TRUE.

Examples

generate_summary(person_record, age)

person_record |>
  dplyr::group_by(sex) |>
  generate_summary(age, stats = c("n", "mean", "median"))

Generate a template

Description

Generate a template

Usage

generate_template(path, template = c("facade", "table-list"))

Arguments

path

A character string specifying the path where the template should be saved. If a directory is provided, the template will be saved with a default name based on the template type.

template

A character string specifying the type of template to generate. Options are "facade" for a YAML facade template or "table-list" for an Excel table list template.

Value

Void. A file path where the template has been saved.

Examples


template_path_facade <- tempfile(fileext = ".yaml")
generate_template(template_path_facade, template = "facade")

template_path_table_list <- tempfile(fileext = ".xlsx")
generate_template(template_path_table_list, template = "table-list")

unlink(template_path_facade)
unlink(template_path_table_list)

Get a facade from the package or a file

Description

Get a facade from the package or a file

Usage

get_tsg_facade(facade = "default", which = c("xlsx", "html", "docx", "pdf"))

Arguments

facade

A character string specifying the name of the facade to retrieve. Defaults to "default". Built-in facades: "default", "yolo", "apa" (horizontal rules only, Times New Roman), "booktabs" (thick top and bottom rules, thin rule under the header), "striped" (coloured header, banded rows) "gridded" (thin lines around every cell), "minimal" (no borders or fills), "financial" (dark blue header, grid, bold last row), "nyt" (editorial, banded), "jama" (medical journal, horizontal rules), "dark" (light text on dark), "pastel" (soft blue accents) and "census" (grey header, small italic notes). An unknown name is an error. Or the path to a .yaml or .json facade file.

Every built-in facade is one file shared by all output formats, so a table looks the same in Excel, HTML, PDF and Word. Only "default" differs per format; the other facades are laid over that format's default. Spreadsheet-only settings (row heights, column widths, grid lines, tab colour, sheet offsets, cell locking) are ignored outside Excel.

which

The output format whose default facade to use: "xlsx" (default), "html", "pdf" (same as "html") or "docx". It only changes the result for "default".

Value

A list containing the facade settings for the specified format. The facade includes styling attributes such as font size, color, border styles, and background fills for different parts of the table.

Examples


# Default facade
get_tsg_facade()

# Other built-in facades
get_tsg_facade("yolo")
get_tsg_facade("booktabs")

Apply numeric cell formatting to a gt table based on facade settings

Description

Mirrors xlsx_decimal_format() for gt output: the columns are chosen by number_format_cols(), decimals use table.decimalPrecision (default 2), and body.numFmt, col_first.numFmt and col_last.numFmt override it.

Usage

gt_apply_numeric_format(gt_tbl, data, facade)

Apply spanner labels to a gt table based on separator-split column names

Description

Apply spanner labels to a gt table based on separator-split column names

Usage

gt_apply_spanners(gt_tbl, col_names, sep, col_labels = NULL)

Apply text decoration (bold/italic/underline) to gt locations

Description

Apply text decoration (bold/italic/underline) to gt locations

Usage

gt_apply_text_decoration(gt_tbl, decoration, locations)

Parse decimal places from an Excel number format string

Description

Returns the number of decimal places encoded in the format string, or NA_integer_ if the string is not a recognised numeric format.

Usage

parse_excel_numfmt_decimals(numfmt)

Arguments

numfmt

A single character string (e.g. "#,##0.00").

Value

An integer scalar, or NA_integer_.


Sample dataset of persons

Description

This is a synthetic dataset containing person information for demonstration purposes.

Usage

person_record

Format

A labelled data frame with 2918 rows and 11 variables:

person_id

Numeric identifier for each person

sex

Factor indicating the sex of the person

age

Numeric age of the person

marital_status

Factor indicating marital status

employed

Employment status

seeing

Functional difficulty in seeing

hearing

Functional difficulty in hearing

walking

Functional difficulty in walking

remembering

Functional difficulty in remembering

self_caring

Functional difficulty in self-caring

communicating

Functional difficulty in communicating

Examples


person_record

Remove data labels

Description

Remove data labels

Usage

remove_label(data, ...)

Arguments

data

A data frame or tibble from which to remove labels.

...

A character vector of column names from which to remove labels. If no columns are specified, all labels will be removed.

Value

A data frame or tibble with the specified labels removed. If no columns are specified, all labels will be removed.

Examples

person_record |>
  generate_frequency(
    seeing,
    hearing,
    walking,
    remembering,
    self_caring,
    communicating
  ) |>
  collapse_list() |>
  remove_label()

Remove all labels

Description

Remove all labels

Usage

remove_labels(data, ...)

Arguments

data

A data frame or tibble from which to remove all labels.

...

A character vector of column names from which to remove labels. If no columns are specified, all labels will be removed.

Value

A data frame or tibble with all labels removed. If no columns are specified, all labels will be removed.

Examples

person_record |>
  generate_frequency(
    seeing,
    hearing,
    walking,
    remembering,
    self_caring,
    communicating
  ) |>
  collapse_list() |>
  remove_labels()

Rename data labels

Description

Rename data labels

Usage

rename_label(data, ...)

Arguments

data

A data frame or tibble to rename labels in.

...

A named list of labels to rename. The names should match the column names in the data, and the values should be the new labels.

Value

A data frame or tibble with the specified labels renamed.

Examples

person_record |>
  generate_frequency(
    seeing,
    hearing,
    walking,
    remembering,
    self_caring,
    communicating
  ) |>
  collapse_list() |>
  rename_label(category = "Functional difficulty")

Convert a tsg table to a flextable object

Description

Internal helper. Builds a flextable from a tsg data frame, detects cross-tabulation spanner headers (columns whose display label contains names_separator), and applies basic facade styling (font, header background, column alignment, decimal precision).

Usage

tsg_to_flextable(
  data,
  names_separator = "__",
  facade = get_tsg_facade(which = "docx")
)

Arguments

data

A tsg or data frame.

names_separator

Separator string for spanner detection. Default "__".

facade

A facade list. Defaults to the global tsg facade.

Value

A flextable object.


Write a tsg table (or list of tables) to a Word (.docx) file

Description

Saves one or more tsg tables as a Word document using the officer and flextable packages (both must be installed).

Usage

write_docx(
  data,
  path,
  ...,
  title = NULL,
  subtitle = NULL,
  source_note = NULL,
  footnotes = NULL,
  separate_files = FALSE,
  names_separator = "__",
  facade = get_tsg_facade(which = "docx")
)

Arguments

data

A tsg or data frame, or a named list of them.

path

File path for the Word output. A .docx extension is added if missing. When separate_files = TRUE the path (minus extension) is used as the directory.

...

Currently unused; reserved for future arguments.

title

Optional title string (overrides data attribute).

subtitle

Optional subtitle string.

source_note

Optional source note string.

footnotes

Optional character vector of footnotes.

separate_files

Logical. When data is a list, FALSE (default) writes all tables into a single combined .docx; TRUE writes one .docx per table inside a subdirectory.

names_separator

Column name separator for detecting cross-tab spanners. Default "__".

facade

A built-in facade name (e.g. "booktabs"; see get_tsg_facade()), the path to a .yaml or .json facade file, or a facade list. A built-in facade looks the same in every output format. Keys missing from it fall back to this format's default facade; settings added with add_facade() take precedence over it.

Details

When data is a named list and separate_files = FALSE (default), all tables are written into a single .docx document, one per page. Set separate_files = TRUE to write one .docx file per table inside a subdirectory derived from path.

Value

Invisibly returns NULL.


Write data to a Google Sheet

Description

Writes data with write_xlsx() and uploads the file to Google Drive, which converts it to a Google Sheet, keeping the facade styling (merged headers, borders, fonts and fills). Requires the googledrive package; sign in with googledrive::drive_auth().

Usage

write_gsheet(data, path, ...)

Arguments

data

A tsg table or a list of them, as for write_xlsx().

path

Where to write. A name or Drive path (e.g. "reports/Table 1") creates a new Google Sheet. An existing sheet, given as googledrive::as_id("<file id>") or a dribble, has its contents replaced in place, so its link stays the same.

...

Arguments passed to write_xlsx(), e.g. facade or include_table_list. separate_files = TRUE is not supported. With include_table_list = TRUE, the links of the table list are rewritten after the upload so they open the right tab in Google Sheets.

Details

Signing in needs access to your Drive files: on Google's consent screen, tick the box to see, edit, create and delete your Google Drive files (it is unticked by default). Without it, writing fails with "(403) Forbidden: Request had insufficient authentication scopes"; sign in again with googledrive::drive_auth(scopes = "https://www.googleapis.com/auth/drive", cache = FALSE) and tick the box.

Value

Invisibly, the Google Sheet as a googledrive::dribble.

Examples

## Not run: 
googledrive::drive_auth()
sheet <- write_gsheet(generate_frequency(person_record, sex), "Sex distribution")

# Replace the contents of the same sheet later; its link stays the same
write_gsheet(generate_frequency(person_record, marital_status), sheet)

## End(Not run)

Write a tsg table (or list of tables) to an HTML file

Description

Saves one or more tsg tables as an HTML file using the gt package (which is already a hard dependency of tsg).

Usage

write_html(
  data,
  path,
  ...,
  title = NULL,
  subtitle = NULL,
  source_note = NULL,
  footnotes = NULL,
  separate_files = FALSE,
  include_table_list = FALSE,
  names_separator = "__",
  facade = get_tsg_facade(which = "html")
)

Arguments

data

A tsg or data frame, or a named list of them.

path

File path for the HTML output. A .html extension is added if missing. When separate_files = TRUE the path (minus extension) is used as the directory.

...

Additional arguments passed to as_gt().

title

Optional title string (overrides data attribute).

subtitle

Optional subtitle string.

source_note

Optional source note string.

footnotes

Optional character vector of footnotes.

separate_files

Logical. When TRUE and data is a list, each table is saved to its own HTML file inside a subdirectory derived from path.

include_table_list

Logical. When TRUE and data is a named list with separate_files = FALSE, prepends a clickable table of contents.

names_separator

Column name separator for spanners. Default "__".

facade

A built-in facade name (e.g. "booktabs"; see get_tsg_facade()), the path to a .yaml or .json facade file, or a facade list. A built-in facade looks the same in every output format. Keys missing from it fall back to this format's default facade; settings added with add_facade() take precedence over it.

Details

When data is a named list and separate_files = FALSE (default), all tables are written into a single self-contained HTML document. Set include_table_list = TRUE to prepend a clickable table-of-contents. Set separate_files = TRUE to write one HTML file per table into a subdirectory.

Value

Invisibly returns NULL.


Write a tsg table (or list of tables) to a PDF file

Description

Saves tables as PDF using gt::gtsave(), which requires the webshot2 package (and a Chromium installation reachable by chromote).

Usage

write_pdf(
  data,
  path,
  ...,
  title = NULL,
  subtitle = NULL,
  source_note = NULL,
  footnotes = NULL,
  separate_files = TRUE,
  names_separator = "__",
  facade = get_tsg_facade(which = "html")
)

Arguments

data

A tsg or data frame, or a named list of them.

path

File path for the PDF output. A .pdf extension is added if missing. When data is a list and separate_files = TRUE, this is used as a directory.

...

Additional arguments passed to as_gt().

title

Optional title string (overrides data attribute).

subtitle

Optional subtitle string.

source_note

Optional source note string.

footnotes

Optional character vector of footnotes.

separate_files

Logical. When data is a list, TRUE (default) saves each table as a separate PDF file inside a subdirectory; FALSE merges them into a single PDF (requires qpdf).

names_separator

Column name separator for spanners. Default "__".

facade

A built-in facade name (e.g. "booktabs"; see get_tsg_facade()), the path to a .yaml or .json facade file, or a facade list. A built-in facade looks the same in every output format. Keys missing from it fall back to this format's default facade; settings added with add_facade() take precedence over it.

Details

When data is a named list, the default (separate_files = TRUE) writes each table to its own .pdf file inside a directory. Set separate_files = FALSE to merge all tables into a single PDF (requires the qpdf package).

Value

Invisibly returns NULL.


Write Data to Excel with Titles, Notes, and Styling

Description

Exports a data frame or a list of data frames to one or multiple Excel files, with support for titles, subtitles, source notes, footnotes, grouping, and custom styles. It leverages the openxlsx package to create styled Excel reports suitable for presentation.

Usage

write_xlsx(
  data,
  path,
  ...,
  sheet_name = NULL,
  trim_sheet_names = FALSE,
  title = NULL,
  subtitle = NULL,
  source_note = NULL,
  footnotes = NULL,
  separate_files = FALSE,
  collapse_list = FALSE,
  row_group_as_column = FALSE,
  names_separator = "__",
  include_table_list = FALSE,
  table_list_reference = NULL,
  facade = get_tsg_facade()
)

Arguments

data

A data.frame, tibble, or a named list of them. When a list is provided:

  • If separate_files = FALSE, each element is written to a separate sheet in one Excel file.

  • If separate_files = TRUE, each element is written to its own Excel file.

path

A file path (if separate_files = FALSE) or directory path (if separate_files = TRUE) where the Excel file(s) will be saved. File extension .xlsx is automatically added if missing.

...

Additional arguments passed to openxlsx::createWorkbook() (e.g. creator) or openxlsx::addWorksheet() (e.g. zoom), matched by name.

sheet_name

Optional name for the Excel sheet. Ignored if data is a list and separate_files = FALSE.

trim_sheet_names

Logical. Excel limits sheet names to 31 characters. If FALSE (default), a longer sheet name (from sheet_name, a list name or the table_name of table_list_reference) is an error. If TRUE, it is cut to 31 characters, and names that then repeat are numbered ("... (2)"). File names (separate_files = TRUE) are never cut.

title

Optional title displayed above the data in each sheet or file.

subtitle

Optional subtitle displayed under the title.

source_note

Optional source note displayed below the data.

footnotes

Optional character vector of footnotes to display below the source note.

separate_files

Logical. If TRUE, each list item in data is saved as a separate Excel file.

collapse_list

Logical. If TRUE, a list of data frames will be merged into one sheet (if applicable).

row_group_as_column

Logical. If TRUE, row groupings are included as columns instead of grouped titles. Applies to a grouped list written on one sheet (collapse_list = TRUE) and to the sheets of a list nested two or more groups deep.

names_separator

Character used to separate column names when dealing with nested or grouped headers.

include_table_list

Logical. If TRUE, a table list reference is included in the Excel file.

table_list_reference

A data frame containing the table list reference. If NULL, it will be generated from data.

facade

A built-in facade name (e.g. "booktabs"; see get_tsg_facade()), the path to a .yaml or .json facade file, or a facade list. A built-in facade looks the same in every output format. Keys missing from it fall back to this format's default facade; settings added with add_facade() take precedence over it.

Details

This function supports advanced Excel formatting including:

The function is designed to handle export needs in professional and reporting contexts.

Value

Invisibly returns NULL. The function is called for its side-effect of writing Excel file(s).

Examples

data <- tsg::generate_frequency(dplyr::starwars, sex)

dir_to <- tempfile()
write_xlsx(
  data,
  file.path(dir_to, "starwars_frequency.xlsx")
 )