| Type: | Package |
| Title: | Beginner-Friendly Statistics and Publication-Ready Tables |
| Version: | 1.0.0 |
| Description: | Provides beginner-friendly functions for common descriptive and inferential statistical analyses, together with tools for creating publication-ready tables. The package includes data description, summary statistics, distribution assessment, group comparisons, effect sizes, correlations, proportions and rates with confidence intervals, crosstabs for epidemiological measures, plots, and modular table-building workflows. Statistical methods include unequal-variance comparisons described by Welch (1947) <doi:10.1093/biomet/34.1-2.28>, score confidence intervals described by Wilson (1927) <doi:10.1080/01621459.1927.10502953>, and robust variance assessment described by Brown and Forsythe (1974) <doi:10.1080/01621459.1974.10482955>. |
| URL: | https://gtstats.thinkdenominator.com/, https://github.com/ThinkDenominator/gtstats |
| BugReports: | https://github.com/thinkdenominator/gtstats/issues |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| LazyData: | true |
| Depends: | R (≥ 4.1.0) |
| Imports: | dplyr, tibble, gt, flextable, officer, stats, ggplot2, tidyselect |
| Suggests: | shiny, rstudioapi, rio, testthat (≥ 3.0.0), knitr, rmarkdown, pkgdown, webshot2 |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-09-11 14:56:33 UTC; drrubesh |
| Author: | Rubeshkumar Polani
|
| Maintainer: | Rubeshkumar Polani <rubesh@thinkdenominator.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-21 21:50:02 UTC |
Add confidence intervals to a summary table
Description
Add confidence intervals to all eligible summaries, or only to selected
variables, without rebuilding the descriptive table. Categorical variables
receive binomial confidence intervals for their displayed proportions.
Continuous variables displayed with a mean receive a t-based confidence
interval for the mean. Median-only summaries are left unchanged because a
distribution-free median interval is not implied by the displayed IQR.
Compact tables show the interval after the estimate without repeating the
confidence level in every cell. Separate tables use concise CI child
columns. The confidence level and interval method are stated once in the
publication footnote.
Usage
add_ci(
x,
vars = NULL,
conf.level = 0.95,
method = c("wilson", "exact"),
digits = NULL,
type = NULL,
estimate = NULL,
numerator = NULL,
denominator = NULL,
sd = NULL,
n = NULL,
se = NULL,
multiplier = 1,
ci_name = NULL
)
Arguments
x |
A table created by |
vars |
Variables that should receive confidence intervals. |
conf.level |
Confidence level. Default is |
method |
Binomial interval method for categorical proportions:
|
digits |
Decimal places for confidence limits. |
type |
For |
estimate, numerator, denominator, sd, n, se |
Columns containing the required
aggregate inputs. Supply bare column names or single character names.
Proportions and rates require |
multiplier |
Positive rate multiplier, such as |
ci_name |
Optional name for the added interval column. The default is
the confidence-level label, for example |
Value
The updated gtstats_summary object.
Examples
summary_table(mtcars, by = am, include = c(mpg, cyl), layout = "separate") |>
add_ci()
summary_table(mtcars, by = am, include = c(mpg, cyl, vs)) |>
add_ci(vars = c(mpg, vs), conf.level = 0.90)
aggregate_rates <- data.frame(
Group = c("A", "B"), Events = c(8, 14), PersonYears = c(420, 510)
)
as_stats_table(aggregate_rates) |>
add_ci(type = "rate", numerator = Events, denominator = PersonYears,
multiplier = 1000)
Add p-values to a descriptive table
Description
Add a p-value column to a descriptive table by comparing each displayed
variable across the grouping variable. P-values are calculated using
compare_groups() and inserted once per variable, with optional superscript
markers indicating which statistical test was used.
Usage
add_p(
x,
test = "auto",
include = tidyselect::everything(),
paired = FALSE,
id = NULL,
distribution_check = TRUE,
var_equal = FALSE,
correction = TRUE,
fisher_seed = 1049L,
p_adjust = c("none", setdiff(stats::p.adjust.methods, "none")),
digits = 3
)
Arguments
x |
A |
test |
Statistical test to use. Either a single test string, or a named character vector/list specifying methods for individual variables. Names may match either displayed variable labels or underlying variable names. |
include |
Variables in the descriptive table for which p-values should
be calculated. Uses tidy-select syntax and defaults to all summarized
variables. For example, |
paired |
Logical; whether comparisons should be treated as paired. |
id |
Pair or participant identifier required when |
distribution_check |
Logical; when |
var_equal |
Logical; for independent, non-skewed continuous comparisons
in |
correction |
Logical; apply continuity correction to chi-square and McNemar tests where applicable. |
fisher_seed |
Integer seed for simulated Fisher exact tests on tables
larger than 2 x 2. Use |
p_adjust |
Multiplicity adjustment applied across displayed variable
tests. One of stats::p.adjust.methods; default |
digits |
Number of decimal places used when formatting p-values. |
Details
This function works only for descriptive tables created in mode = "summary"
and requires a grouping variable supplied via summary_table().
Supported methods include:
-
"auto" -
"welch_t" -
"t_test" -
"wilcox" -
"anova" -
"welch_anova" -
"kruskal" -
"chisq" -
"fisher" -
"mcnemar"
You may also provide a named character vector or named list to specify different methods for individual variables.
Automatic selection and audit trail
With test = "auto", add_p() delegates each comparison to
compare_groups() using the same fixed selection policy: Welch t-test or
Welch ANOVA by default when distribution guidance does not flag skewness;
Student's t-test or classical ANOVA when var_equal = TRUE; rank-based tests
when marked skewness is flagged; and chi-square or Fisher's exact test according to
expected cell counts. For independent ordered factors, automatic mode uses
the same chi-square/Fisher distribution comparison as other categorical
variables; select "wilcox" or "kruskal" explicitly when a rank-based
ordinal comparison is wanted. Shapiro-Wilk is supporting information only
and does not itself select a test.
The publication table contains only the p-value and compact test markers.
The full per-variable audit trail is retained in $assumptions,
$diagnostics, $p_values, and $denominators. In particular,
diagnostics_stats(x) records automatic selection, distribution guidance,
expected cell counts where relevant, and observed group spread for
independent continuous comparisons. Observed spread is descriptive context,
not a variance-test gatekeeper; Welch methods do not require equal
variances.
Value
An updated gtstats_summary object with a p-value column added.
When paired = TRUE, $paired_p_notes records the complete-pair
denominator for each displayed p-value; to_gt() displays this as a
concise p-value footnote.
Examples
summary_table(mtcars, by = am, include = c(mpg, wt, cyl)) |>
add_p()
summary_table(mtcars, by = am, include = c(mpg, wt, cyl)) |>
add_p(test = c(mpg = "welch_t", wt = "wilcox", cyl = "chisq"))
summary_table(mtcars, by = am, include = c(mpg, wt, cyl)) |>
add_p(include = c(mpg, wt))
Add a proportion row to a descriptive table
Description
Add a row showing the proportion of a selected level of a binary,
categorical, or ordinal variable within a gtstats descriptive table.
Usage
add_proportion(
x,
var,
level = NULL,
ci = TRUE,
conf.level = NULL,
ci_method = NULL,
display = NULL,
layout = NULL,
digits = NULL,
label = NULL
)
Arguments
x |
A |
var |
Variable to summarise as a proportion. Can be supplied as a bare name or as a character string. |
level |
Optional level to count. If |
ci |
Logical; whether to display a confidence interval. |
conf.level |
Confidence level for the interval. |
ci_method |
Confidence-interval method: |
display |
Cell display: |
layout |
Table layout. |
digits |
Number of decimal places used when formatting percentages.
|
label |
Optional row label. Defaults to the variable label if available, otherwise the variable name. |
Details
This is useful when you want to highlight a specific category such as
"Yes", "1", or "TRUE" within a Table 1 workflow. The row can be added
overall, by groups, or both, depending on how the descriptive table was
created.
If level = NULL, the function chooses a default level using the following
order:
-
"1" -
"Yes"/"yes" -
"TRUE"/"True"/"true" the second available level for binary variables
otherwise the first available non-missing level
Wilson confidence intervals are used by default. Exact binomial intervals
are available with ci_method = "exact".
Value
An updated gtstats_summary object with a proportion row appended.
Examples
summary_table(mtcars, by = am, overall = TRUE) |>
add_proportion(var = vs)
summary_table(mtcars, by = am, overall = TRUE) |>
add_proportion(var = vs, level = "1", ci = TRUE)
summary_table(mtcars) |>
add_proportion(var = vs, ci = FALSE)
Add an event-rate row
Description
Add an event rate to a table created with summary_table().
Event counts and accumulated time are calculated from complete event-time
pairs only. Event counts and time values must be finite. Exact Poisson
confidence intervals are shown by default. A row with zero accumulated time
is retained as \u2014 and recorded as not estimable in the audit.
Usage
add_rate(
x,
event,
time,
label = NULL,
multiplier = 1000,
time_label = NULL,
ci = TRUE,
conf.level = 0.95,
digits = 1,
layout = NULL
)
Arguments
x |
A |
event |
Non-negative integer event count, supplied as a bare name or character string. Logical values are accepted as binary event indicators. |
time |
Non-negative numeric person-time or exposure-time variable. |
label |
Optional row label. |
multiplier |
Positive rate multiplier. Default is |
time_label |
Optional readable time unit such as |
ci |
Logical; display an exact Poisson confidence interval. |
conf.level |
Confidence level. |
digits |
Number of decimal places. |
layout |
Table layout. |
Details
Rate denominators are tracked separately from ordinary descriptive rows and are stated in the table audit and footnote.
Value
The updated gtstats_summary.
Examples
summary_table(mtcars, by = am, overall = TRUE) |>
add_rate(
event = carb,
time = cyl,
label = "Carburettor rate",
multiplier = 1000
)
# Rates may be added alongside ordinary summaries
summary_table(mtcars, by = am, include = mpg) |>
add_rate(event = carb, time = cyl, multiplier = 1000)
Add a custom row to a descriptive table
Description
Add a user-defined row to a gtstats descriptive table. This is useful for
inserting contextual information such as study period, data source, setting,
or other custom annotations that should appear alongside the main table
content.
Usage
add_row(x, label, overall = NULL, values = NULL, level = "")
Arguments
x |
A |
label |
A single character string giving the row label to display in the
|
overall |
Optional value to display in the |
values |
Optional named character vector or named list giving values for
displayed group columns. Names must match the displayed group column names,
for example |
level |
Optional text to display in the |
Details
The row is matched to the current table structure automatically:
if
overall = TRUE, anOverallcolumn is supportedif
byis used, values must be named using displayed group column namesif neither
overallnorbyis used, a singleValuecolumn is used
Value
An updated gtstats_summary object with the custom row appended.
Examples
res <- summary_table(mtcars, by = am, include = c(mpg, wt), overall = TRUE) |>
add_row(
label = "Study period",
overall = "2020-2024",
values = c("am = 1" = "2020-2024", "am = 0" = "2020-2024")
)
Add summary rows to a descriptive table
Description
Add summary statistics to a gtstats descriptive table builder.
Usage
add_summary(
x,
vars,
statistic = "recommended",
percent = c("column", "row", "overall", "none"),
categorical = c("n_percent", "n_over_N_percent", "n", "percent"),
categorical_layout = c("combined", "separate"),
overall_categorical = c("auto", "n_percent", "n_over_N_percent", "n", "percent"),
show_dichotomous = c("all_levels", "single_row"),
value = NULL,
layout = NULL,
missing = c("ifany", "always", "no", "as_category"),
digits = 1
)
Arguments
x |
A |
vars |
Variables to summarise. Can be supplied as bare names or as a character vector. |
statistic |
Continuous summary selection. A single value
applies to all selected continuous variables. A named character vector can
select a different summary for each variable, for example
|
percent |
Denominator for categorical percentages: |
categorical |
Display for categorical values: |
categorical_layout |
Categorical display layout. |
overall_categorical |
Categorical display used only in the Overall
column. |
show_dichotomous |
How binary variables are displayed. |
value |
Optional named character vector or named list selecting the
event level used when |
layout |
Table layout. |
missing |
Missing-value display and percentage handling. |
digits |
One number applied throughout, or a named numeric vector using
|
Details
This function is the main way to populate a descriptive table with variable
summaries. It supports both grouped and ungrouped tables and can optionally
add an Overall column when the descriptive table was created with
overall = TRUE.
Continuous variables can be displayed in one of four formats:
-
"recommended": mean (SD) or median (IQR) as appropriate -
"mean_sd": mean (SD) -
"mean_se": mean (standard error) -
"mean_ci": mean with a t confidence interval -
"median_iqr": median (IQR) -
"both": mean (SD) and median (IQR)
Variable names may be supplied either as bare names, for example
c(age, sex, bmi), or as a character vector, for example
c("age", "sex", "bmi").
Value
An updated gtstats_summary object with summary rows added.
Examples
summary_table(mtcars, by = am) |>
add_summary(vars = c(mpg, wt, cyl))
summary_table(mtcars, by = am, overall = TRUE) |>
add_summary(vars = c("mpg", "wt", "cyl"))
summary_table(mtcars) |>
add_summary(vars = c(mpg, wt), statistic = "mean_sd")
missing_example <- mtcars
missing_example$vs[1:3] <- NA
summary_table(missing_example) |>
add_summary(vars = vs, missing = "as_category")
Add total counts to a descriptive table
Description
Add a total row to a gtstats descriptive table showing the number of
observations overall or within each displayed group.
Usage
add_total(x, label = "Total (N)", position = c("last", "first"))
Arguments
x |
A |
label |
Row label to display in the |
position |
Position of the total row. Use |
Details
This helper is useful in Table 1 workflows where a final row is needed to
show the number of observations contributing to each column. When the table
includes an Overall column, the total number of rows in the source data is
shown there. When the table is grouped, totals are calculated within each
displayed group. Publication-table headers already display these cohort
denominators automatically, so this row is optional.
This helper can be used only with descriptive tables created in
mode = "summary".
Value
An updated gtstats_summary object with a total row appended.
Examples
summary_table(mtcars, by = am, include = c(mpg, wt, cyl)) |>
add_total()
summary_table(mtcars, by = am, include = c(mpg, wt), overall = TRUE) |>
add_total()
summary_table(mtcars) |>
add_total()
Convert an already summarised data frame into a publication table
Description
Wrap a data frame or tibble containing values that have already been calculated so it can be rendered, styled, and exported with gtstats. No descriptive statistics, confidence intervals, or p-values are calculated or checked by this function.
Usage
as_stats_table(data, notes = NULL)
Arguments
data |
A data frame or tibble containing one row per intended table row. |
notes |
Optional character vector of explanatory notes to display below the table. |
Details
Use summary_table() instead when each row represents a participant or
observation and descriptive statistics still need to be calculated. Use
epi_table() when events and denominators need to be calculated from a line
list or aggregate outbreak/surveillance data.
Value
A gt_data_table object. Use customise_table(), to_flextable(),
to_gt(), or save_output() to present or export it.
Examples
summarised <- mtcars |>
dplyr::summarise(
Cars = dplyr::n(),
`Mean mpg` = mean(mpg),
`Mean weight` = mean(wt)
)
table <- as_stats_table(
summarised,
notes = "Values were calculated before table formatting."
)
customise_table(table, title = "Vehicle summary")
to_flextable(table)
to_gt(table)
Assess the empirical distribution of continuous variables
Description
Assess the empirical distribution of continuous numeric variables to support descriptive reporting. The function describes missingness, finite sample size, skewness, and (optionally) Shapiro-Wilk results. It provides guidance about presenting a variable; it does not select an inferential test.
Usage
assess_distribution(
data,
vars = NULL,
by = NULL,
normality_test = TRUE,
skew_cutoff = 1,
min_n = 3,
plots = FALSE,
digits = 2,
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
vars |
Continuous numeric variables to assess. Bare names or a character vector are accepted. When omitted, all detected continuous variables are assessed. Categorical, ordinal, logical, date-time, and binary variables are rejected when explicitly selected. |
by |
Optional grouping variable, supplied as a bare name or character string. Factors, characters, logical variables, binary variables, and ordinal variables are supported. |
normality_test |
Logical; run Shapiro-Wilk when 3 to 5000 finite
observations are available. Default is |
skew_cutoff |
Positive absolute-skewness threshold for marked skew. |
min_n |
Minimum finite observations required for a shape assessment. |
plots |
Logical; create histogram, density, Q-Q, and box plots. Plots
are stored in |
digits |
Number of decimal places. |
format |
Output format: |
Details
When by is supplied, diagnostics are calculated within every group and one
consistent, variable-level recommendation is also returned in
$recommendations. Shapiro-Wilk is supporting information only: it is
sensitive to sample size and never determines the recommendation by itself.
Value
With format = "table", a gt_distribution object that prints as a
publication-ready table. $summary contains group-level diagnostics and
$recommendations contains one descriptive recommendation per variable.
With format = "tibble", the group-level summary tibble is returned.
Examples
assess_distribution(mtcars, vars = c(mpg, wt))
assess_distribution(mtcars, vars = c(mpg, wt), by = am)
assess_distribution(mtcars, vars = "mpg", normality_test = FALSE)
assess_distribution(mtcars, vars = c("mpg", "wt"), plots = TRUE)$plots
Assess variation of continuous variables across groups
Description
Describe the spread of continuous numeric variables within groups. This is a
diagnostic companion to assess_distribution() and is intended to make
variation visible before a group comparison is interpreted.
Usage
assess_variance(
data,
vars = NULL,
by,
digits = 2,
test = c("levene", "none", "bartlett"),
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
vars |
Continuous numeric variables to assess. Bare names or a character vector are accepted. When omitted, all detected continuous variables are assessed. Categorical, ordinal, logical, date-time, and binary variables are rejected when explicitly selected. |
by |
Grouping variable, supplied as a bare name or character string. It must be categorical, binary, logical, or ordinal and contain at least two observed groups. |
digits |
Number of decimal places. |
test |
Variance hypothesis test to display: |
format |
Output format: |
Details
assess_variance() reports group sample sizes, standard deviations,
variances, and the ratio of the largest to the smallest group SD and
variance. These ratios are descriptive diagnostics, not pass/fail tests.
The function deliberately does not run a variance hypothesis test by
default, and it does not choose an inferential test. Welch t-tests and Welch
ANOVA do not require equal variances for independent groups; this function
does not assess pairing, repeated-measures sphericity, or select a
repeated-measures method.
The default is the median-centred Levene test (often called the
Brown-Forsythe modification) as supporting information. It is less sensitive
to non-normality than Bartlett's test. Set test = "none" for descriptive
spread only, or test = "bartlett" when the normal-distribution assumption
is justified. Neither test is used to select a test in compare_groups().
Value
With format = "table", a gt_variance object that prints as one
readable row per variable: each group's n and SD, the observed SD ratio,
the requested test p-value, and a plain-language interpretation.
$summary contains the full group-level values and $diagnostics retains
technical test metadata. With format = "tibble", the detailed summary
tibble is returned.
Examples
assess_variance(mtcars, vars = c(mpg, wt), by = am)
assess_variance(mtcars, vars = "mpg", by = am, digits = 1)
assess_variance(mtcars, vars = "mpg", by = am, test = "bartlett")
assess_variance(mtcars, vars = "mpg", by = am, test = "levene")
Inspect statistical assumptions
Description
Return a plain-language checklist of items to confirm before reporting a
result. Use view = "audit" to retrieve the underlying technical status and
result codes retained by the analysis object.
Usage
assumptions_stats(
x,
format = c("table", "tibble"),
title = "Checks before reporting",
subtitle = NULL,
view = c("checklist", "audit")
)
Arguments
x |
A |
format |
Output format: |
title, subtitle |
Optional table heading used for |
view |
Either |
Value
A tibble or gt_tbl.
Examples
result <- compare_groups(mtcars, variable = mpg, group = am)
assumptions_stats(result)
assumptions_stats(result, format = "tibble")
Low birth weight data
Description
A labelled and analysis-ready version of the low birth weight study data.
It contains 189 observations and is derived from the dataset distributed in
MASS, originally reported by Hosmer and Lemeshow. Numeric clinical codes
have been converted to readable factors; antenatal_visits is an ordered
factor and the original numeric variables are retained.
Usage
birthwt
Format
A data frame with 189 rows and 12 variables:
- low
Birth-weight outcome: Normal birth weight or Low birth weight.
- age
Maternal age in years.
- lwt
Maternal weight in pounds.
- race
Maternal race.
- smoke
Smoking during pregnancy.
- ptl
Number of previous premature labours.
- ht
History of hypertension.
- ui
Uterine irritability.
- ftv
Number of first-trimester physician visits.
- bwt
Birth weight in grams.
- previous_preterm
Any previous premature labour.
- antenatal_visits
Ordered visit category.
Source
Hosmer, D. W. and Lemeshow, S. (1989). Applied Logistic
Regression. Derived from MASS::birthwt.
Examples
describe_data(birthwt)
summary_table(birthwt, by = low, include = c(age, lwt, smoke), overall = TRUE)
Compare groups using common inferential tests
Description
Compare a variable across groups using a practical set of common inferential tests.
Usage
compare_groups(
data,
variable,
group,
paired = FALSE,
id = NULL,
test = c("auto", "t_test", "welch_t", "wilcox", "anova", "welch_anova", "kruskal",
"chisq", "fisher", "mcnemar", "rm_anova", "friedman", "cochran_q"),
effect_size = FALSE,
conf.level = 0.95,
digits = 2,
var_equal = FALSE,
fisher_seed = 1049L,
format = c("table", "tibble")
)
Arguments
data |
A data.frame. |
variable |
Variable to compare. Can be supplied as a bare name or as a character string. |
group |
Grouping variable. Can be supplied as a bare name or as a character string. |
paired |
Logical; whether the comparison is paired. If |
id |
Pair or participant identifier required when |
test |
Test to use. One of |
effect_size |
Logical; calculate and display the effect size selected
for the comparison structure. Default is |
conf.level |
Confidence level for intervals. |
digits |
Number of decimal places for formatting. |
var_equal |
Logical; for independent, non-skewed continuous outcomes
with |
fisher_seed |
Integer seed used only for simulated Fisher exact tests
on tables larger than 2 x 2. The default makes results reproducible.
Set to |
format |
Output format: |
Details
This function is designed for beginner-friendly and teaching-focused workflows. It combines:
descriptive summaries by group
automatic or user-specified test selection
effect size calculation where supported
a simple display-ready results table
Supported outcome types are:
continuous
binary
categorical
ordinal
Supported tests include:
-
"auto" -
"t_test" -
"welch_t" -
"wilcox" -
"anova" -
"welch_anova" -
"kruskal" -
"chisq" -
"fisher" -
"mcnemar" -
"rm_anova" -
"friedman" -
"cochran_q"
Automatic selection policy
test = "auto" uses the following fixed, data-driven rules. These rules are
intended as transparent defaults, not a substitute for a prespecified
analysis plan.
-
Continuous outcome, two independent groups: Welch t-test by default, or Student's t-test when
var_equal = TRUE, unless marked skewness is flagged in either group, then Wilcoxon rank-sum test. -
Continuous outcome, three or more independent groups: Welch ANOVA by default, or classical one-way ANOVA when
var_equal = TRUE, unless marked skewness is flagged in any group, then Kruskal-Wallis test. -
Paired continuous outcome: for two occasions, paired t-test unless marked skewness in within-pair differences is flagged, then Wilcoxon signed-rank; for three or more occasions, repeated-measures ANOVA unless marked skewness is flagged, then Friedman test. Repeated-measures ANOVA reports a conservative Greenhouse-Geisser-corrected p-value.
-
Independent ordinal, binary, or nominal categorical outcome: Pearson chi-square test when no expected count is below 1 and no more than 20% are below 5; Fisher's exact test otherwise (Monte Carlo p-value for larger tables). This compares the distribution of all levels, which is the usual Table 1 question. Use an explicit rank test (
"wilcox"or"kruskal") when the ordered scale itself is the intended estimand. -
Paired ordinal outcome: Wilcoxon signed-rank for two occasions; Friedman for three or more paired occasions.
-
Paired binary outcome: McNemar test for two occasions; Cochran's Q test for three or more occasions.
Distribution guidance uses the package's skewness assessment within each
group (or within-pair differences). Shapiro-Wilk is supporting information;
it does not by itself change the selected test. Automatic decisions, the
values used, and the selected method are retained in $method,
$diagnostics, and $notes.
For independent continuous comparisons, $diagnostics also reports the
observed standard deviation and variance ratios across groups. These are
descriptive context only: they have no pass/fail threshold and do not alter
automatic test selection. var_equal is a user-specified analytical
assumption, not a variance hypothesis test: gtstats never infers it using
Levene, Bartlett, or F tests. Welch t-tests and Welch ANOVA are the
conservative defaults because they do not require equal variances.
When effect_size = TRUE, the function selects an effect size from the
comparison structure:
Hedges' g for two-group parametric comparisons
rank-biserial correlation for two-group rank comparisons
omega-squared for ANOVA or Welch ANOVA
epsilon-squared for Kruskal-Wallis comparisons
Cramer's V for categorical contingency tables
Hedges' g is accompanied by a large-sample confidence interval. Other
effect-size intervals are omitted unless a supported interval method is
available. Conventional magnitude labels are retained in inferential for
teaching but are not displayed as clinical importance thresholds.
Value
A gt_compare object containing:
-
inputs— function inputs and settings -
descriptives— descriptive summaries by group -
inferential— inferential test results -
table— display-ready results table -
method— metadata on detected variable types -
notes— explanatory notes -
call— matched function call
For paired or repeated analyses, only complete, uniquely matched identifiers
are analysed. The number retained and excluded is available in
$denominators and $notes; rendered tables also identify the complete-pair
denominator. Friedman and Cochran's Q require within-participant variation
and fail clearly when it is absent.
Examples
compare_groups(mtcars, variable = mpg, group = am)
compare_groups(
mtcars,
variable = mpg,
group = am,
effect_size = TRUE
)
compare_groups(
mtcars,
variable = vs,
group = am,
test = "chisq",
effect_size = TRUE
)
compare_groups(
mtcars,
variable = mpg,
group = am,
paired = FALSE,
test = "welch_t"
)
compare_groups(mtcars, variable = mpg, group = am, var_equal = TRUE)
to_gt(compare_groups(mtcars, variable = mpg, group = am))
Correlation analysis for one pair or several continuous variables
Description
correlation() analyses either one prespecified pair (x and y) or a
correlation matrix (vars). Matrix mode uses one method throughout, retains
pairwise sample sizes and inferential results in $summary, and prints a
compact publication-ready matrix. Use plot_correlation() for a shaded
heatmap of a matrix result.
Usage
correlation(
data,
x = NULL,
y = NULL,
method = c("auto", "pearson", "spearman"),
conf.level = 0.95,
digits = 2,
vars = NULL,
triangle = c("lower", "upper", "full"),
order = c("input", "alphabetical", "cluster"),
show_diagonal = TRUE,
display = c("estimate", "estimate_p", "estimate_n", "estimate_p_n", "estimate_ci"),
shade = TRUE,
missing = c("pairwise"),
adjust = c("none", "holm", "bonferroni", "BH"),
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
x, y |
Two continuous variables supplied as bare names or character
strings. Omit these when using |
method |
Correlation method: |
conf.level |
Confidence level for intervals. |
digits |
Number of decimal places used for display. |
vars |
Optional vector of at least two continuous variables, supplied as
|
triangle |
Matrix display: |
order |
Variable order in matrix mode: |
show_diagonal |
Logical; show self-correlations on the diagonal. |
display |
Matrix cell content: correlation |
shade |
Logical; apply coefficient-based shading to the publication
matrix. This affects rendering, not |
missing |
Matrix missing-data rule. Currently |
adjust |
Multiplicity adjustment for matrix p-values: |
format |
Output format: |
Details
In automatic matrix mode, Pearson correlation is used only when every selected variable has absolute sample skewness below 1; otherwise Spearman correlation is used throughout. This is transparent descriptive guidance, not proof of linearity or monotonicity. Inspect the matrix heatmap and relevant pairwise plots before interpretation.
Value
A gt_correlation object. Matrix results additionally inherit from
gt_correlation_matrix and contain a tidy pair-level $summary.
Examples
correlation(mtcars, x = mpg, y = wt)
correlation(mtcars, vars = c(mpg, disp, hp, wt))
plot_correlation(correlation(mtcars, vars = c(mpg, disp, hp, wt)))
Cross-tabulations with optional 2x2 epidemiological measures
Description
Create a publication-ready cross-tabulation for any two categorical variables. Counts, selected row/column/total percentages, and margins are displayed. For a binary 2x2 table, risks, risk ratios, odds ratios, and risk differences are additionally available because their direction is defined. For a 2x2 table, the selected exposed and event levels are always retained in the result, including when they were chosen automatically. Association diagnostics, zero-cell handling, and complete-pair denominators remain in the audit components rather than cluttering the displayed table.
Usage
crosstabs(
data,
row,
col,
percent = "column",
totals = TRUE,
row_level = NULL,
col_level = NULL,
measures = c("rr", "or", "rd"),
conf.level = 0.95,
risk_ci = c("wilson", "exact"),
test = c("auto", "none", "chisq", "fisher"),
zero_correction = c("haldane_anscombe", "none"),
simulate_B = 10000,
digits = 2,
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
row |
Categorical row variable. For a binary 2x2 table, this is the exposure/reference axis. |
col |
Categorical column variable. For a binary 2x2 table, this is the outcome/event axis. |
percent |
Percentages to show in each cell: |
totals |
Logical; include row, column, and grand totals. |
row_level |
Level of |
col_level |
Level of |
measures |
Measures to display: risk, risk ratio ( |
conf.level |
Confidence level for intervals. |
risk_ci |
Risk confidence-interval method: |
test |
Association test: |
zero_correction |
Zero-cell strategy: |
simulate_B |
Number of simulations for the automatic Fisher test in a sparse table larger than 2x2. |
digits |
Number of decimal places. |
format |
Output format: |
Value
A gt_twobytwo object.
Examples
crosstabs(mtcars, row = am, col = vs)
Customize a gtstats table
Description
Apply titles, labels, alignment, emphasis, colours, and a predefined visual
theme to a table produced by gtstats.
Usage
customise_table(
x,
engine = c("flextable", "gt"),
theme = c("default", "journal", "classic", "minimal", "compact"),
title = NULL,
subtitle = NULL,
source_note = NULL,
col_labels = NULL,
row_labels = NULL,
level_labels = NULL,
align = NULL,
hide_cols = NULL,
bold_cols = NULL,
italic_cols = NULL,
font_size = NULL,
font = NULL,
width = NULL,
row_striping = NULL,
accent_color = NULL,
stripe_color = NULL,
bold_labels = TRUE,
show_footnotes = TRUE,
spanning_header = NULL,
footnotes = NULL,
borders = c("horizontal", "all", "minimal"),
density = c("standard", "compact", "spacious"),
column_widths = NULL,
pvalue_style = c("threshold", "fixed", "scientific"),
pvalue_digits = 3,
pvalue_threshold = 0.001,
pvalue_prefix = FALSE
)
Arguments
x |
A supported |
engine |
Rendering engine used when |
theme |
Visual theme: |
title, subtitle |
Optional title and subtitle. |
source_note |
Optional note below the table. |
col_labels, row_labels, level_labels |
Named character vectors for relabelling. |
align |
Named list of left-, right-, or centre-aligned columns. |
hide_cols |
Columns to hide. |
bold_cols, italic_cols |
Columns to emphasise. |
font_size |
Font size in pixels. |
font |
Optional font family. |
width |
Table width as a percentage from 0 to 100. |
row_striping |
Logical; apply alternating row shading. |
accent_color, stripe_color |
Optional table colours. |
bold_labels |
Logical; bold variable labels when rendering a raw result. |
show_footnotes |
Logical; retain explanatory footnotes when rendering a raw result. |
spanning_header |
Optional spanning heading. Supply one character value to span all result columns, or a named list/vector mapping displayed headings to completed column names. |
footnotes |
Optional additional footer notes. |
borders |
Border style: |
density |
Cell density: |
column_widths |
Optional named numeric vector of column widths in inches for flextable output. |
pvalue_style |
P-value style for summary-table results: |
pvalue_digits |
Number of displayed p-value digits. |
pvalue_threshold |
Threshold displayed using a less-than sign. |
pvalue_prefix |
Logical; prepend |
Value
A styled flextable by default, or a gt_tbl when engine = "gt"
or x is already a gt table.
Examples
result <- summary_table(mtcars, include = c(mpg, wt))
customise_table(result, title = "Vehicle characteristics")
Inspect statistical denominators
Description
Return a transparent audit of the observations, missing values, numerators,
denominators, and denominator rules used in a gtstats result.
Usage
denominators_stats(
x,
format = c("table", "tibble"),
title = "Denominator audit",
subtitle = NULL,
view = c("readable", "audit")
)
Arguments
x |
A |
format |
Output format: |
title, subtitle |
Optional table heading used for |
view |
Either |
Value
A tibble or gt_tbl.
Examples
result <- proportion_stats(mtcars, var = vs, by = am)
denominators_stats(result)
Understand a dataset before analysis
Description
Create a concise, clinically oriented first look at a dataset. One row is
returned per variable, combining its label, detected type, completeness,
cardinality, a type-specific overview, and range or levels. Potential
data-quality findings are kept separately in $issues.
Usage
describe_data(data, vars = NULL, digits = 2, format = c("table", "tibble"))
Arguments
data |
A data.frame. |
vars |
Optional character vector of variables. Default is all variables. |
digits |
Number of decimal places in concise numeric summaries. |
format |
Output format: |
Details
describe_data() deliberately does not assess distributional assumptions
or recommend inferential tests. Use assess_distribution() for the shape of
selected continuous variables, summary_table() for detailed descriptive
statistics, and compare_groups() for inferential comparisons.
Value
With format = "table", a gt_describe object that prints as a
publication-ready table. $summary is the concise variable overview and
$issues contains only findings requiring review. With
format = "tibble", the concise summary tibble is returned directly.
Examples
describe_data(mtcars)
describe_data(mtcars, vars = c("mpg", "cyl", "am"))
to_gt(describe_data(mtcars))
Inspect statistical diagnostics
Description
Return diagnostic checks, observed values, thresholds, and interpretations
retained by a gtstats result.
Usage
diagnostics_stats(
x,
format = c("table", "tibble"),
title = "Diagnostics",
subtitle = NULL,
view = c("readable", "audit")
)
Arguments
x |
A |
format |
Output format: |
title, subtitle |
Optional table heading used for |
view |
Either |
Value
A tibble or gt_tbl.
Examples
result <- compare_groups(mtcars, variable = vs, group = am)
diagnostics_stats(result)
Estimate an effect size
Description
Quantify the magnitude of a group difference or association without adding
the full hypothesis-test output produced by compare_groups().
For directional two-group measures, the Contrast column names the grouping
variable and reports first group minus second group. Factor order is therefore
meaningful. Cramer's V and omnibus measures have no direction.
Usage
effect_size(
data,
variable,
group,
method = c("auto", "hedges_g", "rank_biserial", "omega_squared", "epsilon_squared",
"cramers_v"),
paired = FALSE,
id = NULL,
conf.level = 0.95,
interpretation = FALSE,
digits = 2,
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
variable |
Outcome or response variable. |
group |
Grouping variable. |
method |
Effect-size method: |
paired |
Logical; whether the two-group comparison is paired. |
id |
Pair or participant identifier required when |
conf.level |
Confidence level for supported intervals. |
interpretation |
Logical; display a conventional magnitude label. These labels are generic teaching aids and are not clinical importance thresholds. |
digits |
Number of decimal places. |
format |
Output format: |
Details
The default method = "auto" selects one measure from the outcome and
comparison structure:
Hedges' g for two-group parametric comparisons
rank-biserial correlation for two-group rank comparisons
omega-squared for comparisons involving more than two continuous groups
epsilon-squared when a multi-group rank method is requested
Cramer's V for categorical associations
Risk ratios, odds ratios, and risk differences are intentionally not
duplicated here; use crosstabs() for those epidemiological measures.
Value
A publication-ready gt_effect object containing summary, table,
inputs, method, assumptions, diagnostics, denominators, and
notes.
Examples
effect_size(mtcars, variable = mpg, group = am)
effect_size(
mtcars,
variable = mpg,
group = am,
method = "hedges_g",
interpretation = TRUE
)
Outbreak and surveillance summary table
Description
Build a publication-ready epidemiology table from either individual
line-list records or aggregate numerator/denominator data. Unlike
summary_table(), this function always makes the event and denominator
explicit and always reports a confidence interval.
Usage
epi_table(
data,
outcomes = NULL,
by = NULL,
event = NULL,
numerator = NULL,
denominator = NULL,
label = NULL,
person_time = NULL,
measure = c("proportion", "prevalence", "attack_rate", "incidence_rate"),
multiplier = NULL,
ci_method = c("wilson", "exact"),
conf.level = 0.95,
p_value = FALSE,
p_adjust = c("none", "holm", "bonferroni", "BH", "fdr"),
effects = "none",
layout = c("auto", "wide", "long"),
digits = 1,
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
outcomes |
Line-list outcome variables selected with tidyselect syntax. |
by |
Optional grouping variable. |
event |
Event level to count. Supply one value for all outcomes or a
named vector, for example |
numerator, denominator |
Aggregate count and denominator columns. For an
incidence rate, |
label |
Optional aggregate outcome-label column or a single text label. |
person_time |
Optional line-list person-time column. Required when
|
measure |
One of |
multiplier |
Scale used for estimates. Defaults to 100 for proportions, prevalence and attack rates, and 1,000 for incidence rates. |
ci_method |
Binomial interval method: |
conf.level |
Confidence level. |
p_value |
Add an association/rate-comparison p-value when |
p_adjust |
Optional multiplicity adjustment passed to |
effects |
Optional two-group effect measures. Use |
layout |
|
digits |
Number of decimal places. |
format |
|
Value
A gt_epi_table object containing $summary, $table,
$denominators, $p_values, $effects, $inputs, and $notes.
Examples
epi_table(
birthwt, outcomes = low, by = smoke,
event = "Low birth weight", measure = "prevalence"
)
aggregate_data <- data.frame(
ward = c("A", "B"), cases = c(12, 7), population = c(80, 65)
)
epi_table(
aggregate_data, numerator = cases, denominator = population,
by = ward, label = "Influenza", measure = "attack_rate"
)
Launch the gtstats graphical interface
Description
Open a guided Shiny interface for the most common gtstats workflows:
inspecting and preparing a dataset, assessing continuous-variable
distributions and spread, building a summary table, creating outbreak or
surveillance tables, comparing groups, producing correlation tables, and
producing a cross-tabulation. Data can be selected from the current R
environment, loaded from a teaching dataset, or uploaded. Results, plots,
and generated R code can be downloaded. The table customiser can also wrap
an already calculated results data frame with as_stats_table() without
recalculating its values. Excel uploads are available when the suggested
rio package is installed.
Usage
gtstats_app(..., launch.browser = NULL)
Arguments
... |
Additional arguments passed to |
launch.browser |
Logical or a function passed to |
Details
The app is a companion to the package's code-first workflow. It creates reproducible R code for every analysis, so users can begin in the interface and continue in an R script when they are ready.
Shiny is a suggested dependency and is loaded only when gtstats_app() is
called. It is therefore not required for ordinary use of gtstats. While the
app is open, R runs the local Shiny session and the console shows a
Listening on ... message. This is expected. Click Close app in the
bottom-right corner to stop the session cleanly and return to the R prompt.
Value
Invisibly returns the result of shiny::runApp().
Examples
if (interactive()) {
gtstats_app()
}
Oswego foodborne-outbreak line list
Description
A beginner-friendly copy of the 1940 Oswego County church-supper outbreak
line list supplied by the US Centers for Disease Control and Prevention
(CDC) with Epi Info. The 75 interview records are unchanged. Variable names
use snake case, Y/N values are labelled Yes/No, and variable labels
have been added.
Usage
outbreak_data
Format
A data frame with 75 rows and 21 variables. It contains participant
age and sex, illness status and onset information, meal time, and indicators
for foods and drinks consumed. ill is the outcome; food variables such as
vanilla_ice_cream can be used as exposures.
Source
CDC Epi Info teaching data, documented in the Epi Info 6 User's Guide. The source material is a US Government work available without charge. CDC does not endorse gtstats. See the CDC agency materials policy.
Examples
epi_table(
outbreak_data,
outcomes = ill,
by = vanilla_ice_cream,
event = "Yes",
measure = "attack_rate",
p_value = TRUE,
effects = "all"
)
Paired follow-up teaching data
Description
Simulated long-format data for paired analyses. Each participant has a
Baseline and Follow-up record. pain_score supports a paired t-test example,
days_off_work is skewed for a signed-rank example, and symptom_present
supports McNemar's test.
Usage
paired_data
Format
A data frame with 180 rows (90 complete pairs) and 5 variables:
id, visit, pain_score, days_off_work, and symptom_present.
Examples
compare_groups(
paired_data, variable = pain_score, group = visit,
paired = TRUE, id = id
)
compare_groups(
paired_data, variable = symptom_present, group = visit,
paired = TRUE, id = id
)
Plot a group comparison
Description
Create a publication-ready comparison plot using a sensible visual selected from the outcome type and study design.
Usage
plot_compare(
data,
variable,
group,
paired = FALSE,
id = NULL,
type = c("auto", "box", "bar"),
display = c("proportion", "count"),
show_points = TRUE,
show_p = FALSE,
test = c("auto", "t_test", "welch_t", "wilcox", "anova", "welch_anova", "kruskal",
"chisq", "fisher", "mcnemar", "rm_anova", "friedman", "cochran_q"),
var_equal = FALSE,
palette = NULL,
base_size = 14,
title = NULL,
caption = NULL,
xlab = NULL,
ylab = NULL,
legend_title = NULL
)
Arguments
data |
A data frame. |
variable |
Outcome or response variable, supplied as a bare name or character string. |
group |
Categorical grouping variable, supplied as a bare name or character string. |
paired |
Logical; whether observations are paired or repeatedly measured. |
id |
Participant identifier required when |
type |
Plot type: |
display |
Categorical display: within-group |
show_points |
Logical; show individual observations for continuous data. |
show_p |
Logical; add the selected test and p-value as a plot caption. |
test |
Test passed to |
var_equal |
Logical; passed to |
palette |
Optional character vector of colours. It must contain at least one colour per displayed group or outcome level. |
base_size |
Base font size. |
title, caption |
Optional plot title and caption. |
xlab, ylab |
Optional axis labels. |
legend_title |
Optional legend title. |
Details
The minimal call is plot_compare(data, variable, group). Continuous outcomes
are shown as boxplots with individual observations, categorical outcomes as
stacked within-group proportions, and paired continuous outcomes as
participant-level connected observations. The returned object is a standard
ggplot and can be customized with ordinary ggplot2 layers.
When show_p = TRUE, the annotation is obtained from compare_groups() with
the same test, var_equal, paired, and id settings. The test name is always shown
with the p-value. The annotation and plotted denominators use the same
complete observations; non-finite continuous values are excluded.
Value
A ggplot object.
Examples
plot_compare(mtcars, variable = mpg, group = am)
plot_compare(
mtcars,
variable = vs,
group = am,
display = "proportion",
show_p = TRUE
)
Plot the relationship between two continuous variables
Description
Create a publication-ready scatterplot that is aligned with
correlation(). The minimal call is plot_correlation(data, x, y).
Incomplete pairs are excluded and the analysed number of complete pairs is
shown in the caption.
Usage
plot_correlation(
data,
x = NULL,
y = NULL,
method = c("auto", "pearson", "spearman"),
trend = c("auto", "linear", "smooth", "none"),
show_ci = TRUE,
show_correlation = FALSE,
conf.level = 0.95,
digits = 2,
point_color = "#4472C4",
line_color = "#ED7D31",
base_size = 14,
title = NULL,
caption = NULL,
xlab = NULL,
ylab = NULL,
triangle = NULL,
show_diagonal = NULL,
show_values = TRUE,
low_color = "#355C7D",
mid_color = "#FFFFFF",
high_color = "#C06C5B"
)
Arguments
data |
A data frame, or a matrix result returned by |
x, y |
Continuous variables, supplied as bare names or character strings. |
method |
Correlation method: |
trend |
Fitted trend: |
show_ci |
Logical; display the confidence band around a fitted trend. |
show_correlation |
Logical; report the correlation result in the caption. |
conf.level |
Confidence level passed to |
digits |
Number of decimal places used in the correlation annotation. |
point_color, line_color |
Colours used for observations and the trend. |
base_size |
Base font size. |
title, caption |
Optional plot title and caption. |
xlab, ylab |
Optional axis labels. |
triangle |
Matrix cells to show when |
show_diagonal |
Logical; show self-correlations in a matrix heatmap.
The matrix object's setting is inherited when |
show_values |
Logical; print coefficients inside heatmap cells. |
low_color, mid_color, high_color |
Colours used by the matrix heatmap. |
Details
With trend = "auto", a linear trend is used for Pearson correlation and a
smooth trend for Spearman correlation. Set trend = "none" to display the
observations alone. When show_correlation = TRUE, the caption reports the
same method, coefficient, confidence interval when available, and p-value as
correlation(). The returned object is a standard ggplot, so ordinary
ggplot2 layers can be added.
Value
A ggplot object.
Examples
plot_correlation(mtcars, x = mpg, y = wt)
plot_correlation(
mtcars,
x = mpg,
y = wt,
show_correlation = TRUE
)
matrix_result <- correlation(mtcars, vars = c(mpg, disp, hp, wt))
plot_correlation(matrix_result)
Print a gtstats compare object
Description
Print a publication-ready comparison table.
Usage
## S3 method for class 'gt_compare'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The print method renders the concise publication table. Detailed numerical results and audit information remain available in the object components.
Value
The input object, invisibly.
Examples
x <- compare_groups(mtcars, variable = mpg, group = am)
print(x)
Print a gtstats correlation object
Description
Print a publication-ready correlation table.
Usage
## S3 method for class 'gt_correlation'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
Detailed numerical results and audit information remain available in the object components.
Value
The input object, invisibly.
Examples
x <- correlation(mtcars, x = mpg, y = wt)
print(x)
Print an already summarised gtstats table
Description
Print an already summarised gtstats table
Usage
## S3 method for class 'gt_data_table'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to |
Value
The input object, invisibly.
Print a gtstats describe object
Description
Print the publication-ready table stored by a gt_describe object.
Usage
## S3 method for class 'gt_describe'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The underlying concise tibble remains available in $summary, and focused
data-quality findings are available in $issues.
Value
The input object, invisibly.
Examples
x <- describe_data(mtcars)
print(x)
Print a gtstats distribution object
Description
Print publication-ready distribution diagnostics and recommendations.
Usage
## S3 method for class 'gt_distribution'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The detailed diagnostic table includes the suggested presentation beside the
numerical diagnostics. With groups, the common variable-level suggestion is
shown once beside the first group row. Machine-readable results remain
available in $summary and $recommendations.
Value
The input object, invisibly.
Examples
x <- assess_distribution(mtcars, vars = c("mpg", "wt"))
print(x)
Print a gtstats effect-size object
Description
Print the publication-ready table stored by a gt_effect object.
Usage
## S3 method for class 'gt_effect'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to |
Value
The input object, invisibly.
Examples
x <- effect_size(mtcars, variable = mpg, group = am)
print(x)
Print an outbreak and surveillance table
Description
Print an outbreak and surveillance table
Usage
## S3 method for class 'gt_epi_table'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to |
Value
The input object, invisibly.
Print a gtstats proportion object
Description
Print a compact console preview of a gt_prop object.
Usage
## S3 method for class 'gt_prop'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The print method shows the dataset name, variable, selected level, optional grouping variable, and the display-ready proportion table.
Value
The input object, invisibly.
Examples
x <- proportion_stats(mtcars, var = vs, by = am)
print(x)
Print a gtstats rate object
Description
Print a compact console preview of a gt_rate object.
Usage
## S3 method for class 'gt_rate'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The print method shows the dataset name, event variable, person-time variable, optional grouping variable, and the display-ready rate table.
Value
The input object, invisibly.
Examples
df <- data.frame(
event = c(1, 0, 1, 0, 1, 1),
ptime = c(10, 12, 8, 9, 11, 7),
arm = c("A", "A", "A", "B", "B", "B")
)
x <- rate_stats(df, event = event, time = ptime, by = arm)
print(x)
Print a gtstats 2x2 table object
Description
Print a compact console preview of a gt_twobytwo object.
Usage
## S3 method for class 'gt_twobytwo'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
The print method shows the dataset name, row/reference definition, column/event definition, and the display-ready 2x2 epidemiology table.
Value
The input object, invisibly.
Examples
x <- crosstabs(mtcars, row = am, col = vs)
print(x)
Print a gtstats variance object
Description
Print publication-ready variance diagnostics. Group-level sample sizes,
standard deviations, variances, and observed spread ratios are displayed;
the underlying values and explanatory metadata remain available in
$summary and $diagnostics.
Usage
## S3 method for class 'gt_variance'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Value
The input object, invisibly.
Examples
x <- assess_variance(mtcars, vars = c(mpg, wt), by = am)
print(x)
Print a descriptive table
Description
Print a completed gtstats_summary as a publication-ready flextable.
An empty builder instead prints a short instruction explaining how to add
rows.
Usage
## S3 method for class 'gtstats_summary'
print(x, ...)
Arguments
x |
A |
... |
Further arguments passed to methods. |
Details
Use format = "tibble" in summary_table() for a plain console table, or
call to_gt() when an HTML-oriented gt table is required.
Value
The input object, invisibly.
Examples
x <- summary_table(mtcars, by = am, overall = TRUE)
print(x)
Proportion statistics
Description
Calculate a proportion and confidence interval, optionally within groups.
This is the descriptive-statistics counterpart to rate_stats().
Usage
proportion_stats(
data,
var,
by = NULL,
level = NULL,
conf.level = 0.95,
ci_method = c("wilson", "exact"),
display = c("n_percent", "percent", "n_over_N_percent"),
digits = 1,
format = c("table", "tibble")
)
Arguments
data |
A data frame. |
var |
Binary or categorical variable whose selected level is counted. |
by |
Optional categorical grouping variable. |
level |
Outcome level to count. A sensible event level is selected when omitted. |
conf.level |
Confidence level for the interval. |
ci_method |
Confidence-interval method: |
display |
Estimate display: |
digits |
Number of decimal places. |
format |
Output format: |
Value
A gt_prop object containing numeric results and a display table.
Examples
proportion_stats(mtcars, var = vs)
proportion_stats(mtcars, var = vs, by = am)
Incidence rate with exact Poisson confidence interval
Description
Compute an incidence or event rate with exact Poisson confidence intervals, either overall or within groups defined by a categorical variable.
Usage
rate_stats(
data,
event,
time,
by = NULL,
multiplier = 1000,
time_label = NULL,
conf.level = 0.95,
digits = 1,
format = c("table", "tibble")
)
Arguments
data |
A data.frame. |
event |
Event variable. Can be supplied as a bare name or as a
character string. May be binary ( |
time |
Person-time variable. Can be supplied as a bare name or as a character string. Must be numeric and non-negative. |
by |
Optional grouping variable. Can be supplied as a bare name or as a character string. |
multiplier |
Numeric multiplier used to scale the rate, for
example |
time_label |
Optional readable unit for accumulated time, such as
|
conf.level |
Confidence level for the interval. Default is
|
digits |
Number of decimal places used when formatting rates.
Default is |
format |
Output format: |
Details
This function is designed for simple epidemiological summaries where
events are counted over a denominator of person-time. The event
variable may be a binary indicator, a logical variable, or a count
variable. The time variable must be numeric, finite, and non-negative.
A zero accumulated person-time denominator is retained and clearly marked as
not estimable rather than silently converted to a rate.
When a grouping variable is supplied, rates are calculated
separately within each group. Confidence intervals are calculated
using stats::poisson.test().
The publication table uses each group as a spanning header, with separate
columns for events, accumulated time, rate, and confidence interval. The
tidy long-form numerical results remain available in $summary.
Value
A gt_rate object containing:
-
inputs— function inputs and settings -
summary— detailed summary table -
table— display-ready table -
notes— explanatory note -
call— matched function call
Examples
df <- data.frame(
event = c(1, 0, 1, 0, 1, 1),
ptime = c(10, 12, 8, 9, 11, 7),
arm = c("A", "A", "A", "B", "B", "B")
)
rate_stats(df, event = event, time = ptime)
rate_stats(df, event = event, time = ptime, by = arm)
to_gt(rate_stats(df, event = event, time = ptime, by = arm))
Save a gtstats table or plot
Description
Save a gtstats result, rendered flextable, rendered gt_tbl, or
ggplot2 plot. A named list of gtstats results, flextables, and plots can be
combined into one Word document. The object determines the export route
automatically. The file type is inferred from filename.
Usage
save_output(
x,
filename,
path = NULL,
title = NULL,
subtitle = NULL,
bold_labels = TRUE,
show_footnotes = TRUE,
zoom = 2,
expand = 5,
vwidth = 992,
vheight = 744,
width = 8,
height = 6,
units = "in",
dpi = 300,
bg = "white",
page_break = TRUE,
quiet = FALSE,
...
)
Arguments
x |
A |
filename |
Output filename including a supported extension. |
path |
Optional output directory. A bare |
title, subtitle |
Optional table title and subtitle. |
bold_labels |
Logical; bold variable labels in tables. |
show_footnotes |
Logical; include explanatory table footnotes. |
zoom, expand |
Image-export controls for tables. |
vwidth, vheight |
Browser viewport dimensions for table image export. |
width, height |
Plot dimensions. |
units |
Dimension units passed to |
dpi |
Output resolution for plots. |
bg |
Plot background colour. |
page_break |
Logical; when saving a list to Word, start each output after the first on a new page. |
quiet |
Logical; suppress the saved-path message. |
... |
Additional arguments passed to the relevant underlying save method. |
Value
The normalized saved path, invisibly.
Examples
table <- summary_table(mtcars) |> add_summary(vars = c(mpg, wt))
save_output(table, "summary.html", path = tempdir())
plot <- plot_compare(mtcars, variable = mpg, group = am)
save_output(plot, "comparison.png", path = tempdir())
save_output(
list("Table 1" = table, "Comparison plot" = plot),
"statistical-report.docx",
path = tempdir()
)
Create a summary table builder
Description
Create the descriptive foundation of a publication-ready table. Add further
layers only when needed: add_ci() for confidence intervals, add_p() for
statistical comparisons, and specialist helpers such as add_proportion(),
add_rate(), add_total(), and add_row().
Usage
summary_table(
data,
by = NULL,
include = NULL,
overall = FALSE,
statistic = "recommended",
categorical = c("n_percent", "n_over_N_percent", "n", "percent"),
categorical_layout = c("combined", "separate"),
show_dichotomous = c("all_levels", "single_row"),
value = NULL,
percent = c("column", "row", "overall"),
overall_categorical = c("auto", "n_percent", "n_over_N_percent", "n", "percent"),
digits = 1,
missing = c("ifany", "always", "no", "as_category"),
layout = c("compact", "separate"),
label = NULL,
conf.level = 0.95,
format = c("table", "tibble")
)
Arguments
data |
A data.frame. |
by |
Optional grouping variable. Can be supplied as a bare name or as a character string. The grouping variable must be categorical, binary, or ordinal. |
include |
Optional variables to summarise immediately. Supply bare
names, such as |
overall |
Overall-column setting. Use |
statistic |
Continuous summary format: |
categorical |
Categorical display: |
categorical_layout |
Categorical column layout. |
show_dichotomous |
Binary-variable display. |
value |
Optional named character vector or list selecting the event
level for compact binary rows, for example |
percent |
Percentage denominator: |
overall_categorical |
Categorical display in the Overall column.
|
digits |
One number applied throughout, or a named numeric vector using
|
missing |
Missing-value display and percentage handling. |
layout |
Table layout. |
label |
Optional named character vector overriding variable labels. |
conf.level |
Confidence level used when |
format |
Display format: |
Details
For the usual Table 1 workflow, select all variables together with
include. Continuous, binary, categorical, and ordinal variables are
detected automatically and added using beginner-friendly defaults. There is
no need to add continuous and categorical variables separately.
When include = NULL, an empty builder is returned for specialist row-only
workflows. Printing a completed object automatically displays a
publication-ready flextable; call to_gt() when an HTML-oriented gt
table is required.
A grouping variable may be supplied to create one column per group.
An optional overall column can also be requested for later use.
Value
A gtstats_summary object containing the source data,
structural settings, and placeholders for table components.
Examples
summary_table(
mtcars,
by = am,
include = c(mpg, wt, cyl, vs),
overall = TRUE
)
summary_table(
mtcars,
by = am,
include = c(mpg, wt, cyl, vs),
overall = TRUE
) |>
add_p()
# Percentages without decimals and Overall displayed last
summary_table(
mtcars,
by = am,
include = c(mpg, wt, cyl, vs),
overall = "last",
digits = c(continuous = 1, percent = 0)
)
# Add confidence intervals as a visible layer
summary_table(
mtcars,
include = c(cyl, vs),
categorical = "percent",
layout = "separate"
) |>
add_ci()
# Compact binary rows, with an explicit event where required
summary_table(
mtcars,
include = c(mpg, vs, am),
show_dichotomous = "single_row",
value = c(vs = "1", am = "1")
)
# Include Missing in a categorical percentage denominator
missing_example <- mtcars
missing_example$vs[1:3] <- NA
summary_table(
missing_example,
include = vs,
missing = "as_category"
)
Archived weekly US hospital-admission surveillance data
Description
A teaching extract from CDC's archived weekly United States COVID-19
hospital-admission surveillance dataset. It contains one record per health
service area for the report dated 12 January 2024. The CDC county file
repeats the same area-level metrics for each constituent county; this copy
retains one exact metric record per health service area to prevent double
counting. Names and labels were simplified, dates were parsed, and the
source spelling Insuficient Data was corrected in the factor label.
Usage
surveillance_data
Format
A data frame with 808 rows and 9 variables:
- health_service_area_id
CDC health service area identifier.
- population
Health service area population used as denominator.
- report_date
CDC report date.
- week_end_date
End date of the surveillance week.
- mmwr_week
MMWR epidemiological week.
- mmwr_year
MMWR year.
- admissions
Weekly confirmed COVID-19 hospital admissions.
- admissions_per_100k
CDC-published weekly rate per 100,000.
- admission_level
CDC admission-level category.
Two areas have insufficient admission data and therefore missing counts and rates. The archived values are provisional teaching data and should not be used to describe current disease activity.
Source
CDC, Weekly United States COVID-19 Hospitalization Metrics by County - ARCHIVED, dataset akn2-qxic.
The metadata identifies this dataset as USGOV_WORKS; it is available
without charge. CDC does not endorse gtstats. See the CDC
agency materials policy.
Examples
complete_surveillance <- subset(surveillance_data, !is.na(admissions))
epi_table(
complete_surveillance,
numerator = admissions,
denominator = population,
label = admission_level,
measure = "incidence_rate",
multiplier = 100000
)
Convert a gtstats object to flextable
Description
Convert a supported gtstats object into a flextable for use in
Word, PowerPoint, and other Office-style outputs.
Usage
to_flextable(
x,
font_size = 10,
font = NULL,
autofit = TRUE,
show_footnotes = TRUE,
title = NULL,
subtitle = NULL
)
Arguments
x |
A supported |
font_size |
Font size applied to the whole table. Default is
|
font |
Optional font family applied to the whole table. |
autofit |
Logical; whether column widths should be adjusted
automatically using |
show_footnotes |
Logical; include concise explanatory footnotes. |
title, subtitle |
Optional title and subtitle placed above the table. |
Details
This function is intended for export workflows where a gtstats
object needs to be inserted into a report or presentation. The input
should be the original analytical object, not the rendered gt table
returned by to_gt().
Text columns are left-aligned and value columns are right-aligned. Notes, footnotes, and p-value method footnotes are appended to the footer when available.
Value
A flextable object.
Examples
res <- summary_table(mtcars, by = am, overall = TRUE) |>
add_summary(vars = c(mpg, wt, cyl)) |>
add_total() |>
add_p()
to_flextable(res)
Convert a gtstats result to a gt table
Description
Render supported gtstats objects as formatted gt tables.
Usage
to_gt(
x,
title = NULL,
subtitle = NULL,
bold_labels = TRUE,
show_footnotes = TRUE
)
Arguments
x |
A supported |
title |
Optional table title. |
subtitle |
Optional table subtitle. |
bold_labels |
Logical; whether to bold variable labels where appropriate. |
show_footnotes |
Logical; whether explanatory footnotes should be displayed. |
Details
This function is the explicit rendering bridge between analytical
gtstats objects and presentation-ready table output. It supports
descriptive, inferential, epidemiological, and table-builder
objects created by the package and applies a consistent visual
style using gt.
Supported inputs include:
-
gt_describe -
gt_distribution -
gt_variance -
gt_compare -
gt_correlation -
gt_effect -
gt_prop -
gt_rate -
gt_twobytwo -
gtstats_summary -
gt_data_table
Value
A gt_tbl object.
Examples
to_gt(describe_data(mtcars))
to_gt(summary_table(mtcars, by = am, include = c(mpg, wt)))
to_gt(compare_groups(mtcars, variable = mpg, group = am))
to_gt(
summary_table(
mtcars,
by = am,
include = c(mpg, wt, cyl),
overall = TRUE
) |>
add_total() |>
add_p()
)
Three-arm clinical trial teaching data
Description
Simulated data for demonstrating independent-group analyses. The dataset is intentionally constructed to include approximately symmetric continuous outcomes, a right-skewed outcome, an ordinal outcome, common and rare binary outcomes, correlated biomarkers, and person-time with event counts.
Usage
trial_data
Format
A data frame with 180 rows and 13 variables. arm has three groups;
change_score is approximately symmetric; hospital_days is right-skewed;
response is ordered; rare_event is sparse; and followup_years with
infection_events supports rate examples.
Examples
compare_groups(trial_data, variable = change_score, group = arm)
compare_groups(trial_data, variable = hospital_days, group = arm)
compare_groups(trial_data, variable = rare_event, group = arm)