| Title: | Produces Publication-Ready Summary Tables and Plots |
| Version: | 1.0.0 |
| Description: | Produces tables with descriptive statistics for continuous, categorical and dichotomous variables. It is largely based on the package 'gtsummary'; Sjoberg DD et al. (2021) <doi:10.32614/RJ-2021-053>. The tables can be accompanied by matching boxplots, line plots and stacked barplots, also over time. |
| License: | LGPL-3 |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.2 |
| Depends: | R (≥ 4.1) |
| Imports: | Hmisc, cardx, dplyr, gtsummary (≥ 2.3.0), forcats, labelled, purrr, rlang, tidyr, flextable, officer, graphics, grDevices, stats, utils, tools |
| Suggests: | broom (≥ 1.0.8), knitr, survival, testthat (≥ 3.0.0), rmarkdown |
| VignetteBuilder: | knitr |
| URL: | https://sakk-statistics.github.io/summarySCI/, https://github.com/SAKK-Statistics/summarySCI |
| BugReports: | https://github.com/SAKK-Statistics/summarySCI/issues |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-13 15:02:39 UTC; charlottemi |
| Author: | Sämi Schär [aut], Charlotte Micheloud [cre, aut], Tudor Jumuga [aut] |
| Maintainer: | Charlotte Micheloud <Charlotte.Micheloud@swisscancerinstitute.ch> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-13 16:10:08 UTC |
Convert a character vector to a factor with natural level order
Description
Convert a character vector to a factor with natural level order
Usage
as_natural_factor(x)
Arguments
x |
A character vector. |
Value
A factor; the "label" attribute is kept.
Boxplot over time
Description
Generates boxplots over time for one or multiple sub-groups.
Usage
boxplotSCI(
data,
var,
order = NULL,
visit = NULL,
group = NULL,
group_names = NULL,
group_names_short = NULL,
main = "",
xlab = NULL,
ylab = "Variable",
ylim = NULL,
y_ticks = NULL,
col = NULL,
cex_lab = 1,
cex_axis = 1,
cex_n_patients = 0.7,
boxwex = NULL,
shift = NULL,
mar_custom = NULL,
xlab_line = NULL,
ylab_line = 3,
xlab_position = NULL,
lines = NULL,
lty = NULL,
col_lines = NULL,
legend_position = "topright",
legend_offset = c(0, 0),
legend_cex = 1,
legend_bty = "n",
risk_table = NULL,
missing_nr = 0,
color_time = FALSE,
stat_footnote = FALSE,
...
)
Arguments
data |
A data frame or tibble containing the data to be plotted. |
var |
Name of the column in |
order |
Name of the column in |
visit |
Name of the column in |
group |
Name of the column in |
group_names |
A character vector containing the names of the groups
to be displayed in the legend. The order must match |
group_names_short |
A character vector containing short names or abbreviations
for the groups, to be displayed below the x-axis near the patient counts.
Optional. Defaults to |
main |
Title of the plot. Defaults to |
xlab |
A label for the x-axis. Default is |
ylab |
A label for the y-axis. Default is |
ylim |
The y-axis limits of the plot as a numeric vector of length 2.
Default is |
y_ticks |
A numeric vector specifying the explicit tick positions on the
y-axis. Default is |
col |
A character vector of hex colors or color names to use for the boxes.
Default is |
cex_lab |
A numeric value specifying the font size of the main axis labels. Default is |
cex_axis |
A numeric value specifying the font size of the axis tick marks. Default is |
cex_n_patients |
A numeric value specifying the font size of the sample size
labels and numbers displayed beneath the horizontal axis. Default is |
boxwex |
Scale factor for the width of the boxes. Default is |
shift |
A numeric value indicating the distance between adjacent boxes
within a timepoint cluster. Default is |
mar_custom |
A numeric vector indicating the plot margins to be used in
the form |
xlab_line |
A numeric value indicating the margin line offset for the x-axis label.
Default is |
ylab_line |
A numeric value indicating the margin line offset for the y-axis label.
Default is |
xlab_position |
Horizontal position coordinate adjustment for the sample size
group headers down the left-hand margin. Default is |
lines |
A numeric vector indicating the vertical coordinates where horizontal reference lines will be plotted. Optional. |
lty |
A numeric vector of length 1 or of the same length as |
col_lines |
A character vector of length 1 or of the same length as
|
legend_position |
Position of the legend box. Options include standard base R
keywords (e.g., |
legend_offset |
A numeric vector of length 2 specifying an |
legend_cex |
A numeric value specifying the font and element scaling size
inside the legend box. Default is |
legend_bty |
The type of box border to be drawn around the legend.
Allowed values are |
risk_table |
A logical toggle switch enabling the patient numbers
(non-missing observations of |
missing_nr |
A numeric or character value indicating how zero-count patient
sizes on the x-axis should be displayed. Default is |
color_time |
A logical toggle switch enabling legacy timepoint colorization. Supports
legacy use, where, for a single timepoint, multiple groups were used as "timepoint" variable.
If set to |
stat_footnote |
Show what the plot displays as a footnote in the
bottom-right corner, beneath the x-axis title: |
... |
Further graphical parameters passed on to |
Details
The box spans the first to the third quartile with the median inside,
computed as in the summary tables (summaryTable(), summaryByVisit():
quantile(type = 2)), so that a boxplot and a "median_IQR" table show
the same numbers. (boxplot() itself draws Tukey's hinges, which can differ
slightly.) The whiskers reach the most extreme values within range (1.5 by
default) times the box length from the box; values beyond are drawn as
points.
Examples
library(summarySCI)
data("hemoglobin_data")
boxplotSCI(data = hemoglobin_data,
var = hb,
order = visit_nr,
group = Arm,
group_names = c("Treatment (Arm A)", "Control (Arm B)"),
group_names_short = c("A", "B"),
# Title
main = "Hemoglobin over time",
# Col of boxes
col = c("lightblue", "orange"),
# X axis label
xlab = "Visits",
# X axis position
xlab_position = 0,
# Y axis label
ylab = "Score",
lines = c(90, 120, 160),
# Col of lines
col_lines = c("red", "grey", "red"),
# Type of lines
lty = c(2, 3, 2)
)
Digits for the categorical statistics
Description
Counts (n, N) are shown without decimals; digits_cat is used for the
percentages only. The digits are returned in the order of the statistics
in stat_fmt, as gtsummary expects.
Usage
cat_digits(stat_fmt, digits_cat)
Arguments
stat_fmt |
Statistic string, e.g. |
digits_cat |
Digits for percentages. |
Value
Integer vector, one value per statistic.
Resolve a column-name argument
Description
Turns the argument of a plotting function into column name(s). Accepts
quoted names ("x", c("x", "y")), a variable holding such names, and
bare names (x): a bare name does not evaluate to a character vector, so
it is deparsed instead.
Usage
col_names(sub, val_fun)
Arguments
sub |
The unevaluated argument, i.e. |
val_fun |
A function evaluating the argument, i.e. |
Value
A character vector, or NULL if the argument is NULL.
Digits for the continuous statistics
Description
digits_cont for every statistic, except the geometric SD: a factor close
to 1 (e.g. 1.13), which gets at least 2 decimals. The digits are returned
in the order of the statistics in stat_fmt, as gtsummary expects.
Usage
cont_digits(stat_fmt, digits_cont)
Arguments
stat_fmt |
Statistic string, e.g. |
digits_cont |
Digits for continuous statistics. |
Value
Integer vector, one value per statistic.
Robust Fisher's exact test for gtsummary::add_p()
Description
Runs stats::fisher.test(); if it fails because the FEXACT workspace is too
small (tables with many levels), retries with a larger workspace and finally
falls back to a Monte Carlo p-value (reproducible with set.seed()).
Returns NA if the table is degenerate.
Usage
fisher_test_safe(data, variable, by, ...)
Arguments
data, variable, by |
Passed by gtsummary::add_p(). |
Value
A data frame with columns p.value and method.
Geometric mean
Description
This function return the geometric mean. It is only defined for positive
values: if x contains zeros or negative values, NA is returned with a
warning (instead of silently dropping them, which log() and na.rm would
otherwise do).
Usage
geom_mean(x, na.rm = TRUE)
Arguments
x |
Numeric vector |
na.rm |
Logical; whether missing values are removed first. |
Value
Geometric mean
Geometric standard deviation
Description
The standard deviation on the log scale, back-transformed:
exp(sd(log(x))). It is a factor: about two thirds of log-normal values lie
between the geometric mean divided and multiplied by it. Like geom_mean(),
it is only defined for positive values and is NA otherwise (without a
second warning), and NA for fewer than two values.
Usage
geom_sd(x, na.rm = TRUE)
Arguments
x |
Numeric vector |
na.rm |
Logical; whether missing values are removed first. |
Value
Geometric standard deviation
Get the labels from a dataset
Description
This function get the labels from a dataset
Usage
get_labels(data, vars)
Arguments
data |
Dataset |
vars |
Variables of interest |
Value
The labels
Hemoglobin data (to illustrate boxplotSCI() and summaryByVisit())
Description
A dataset containing the hemoglobin value of 169 patients over 9 visits. Adapted from SAKK 08/14.
Usage
data(hemoglobin_data)
Format
hemoglobin_data
A data frame with 1307 rows and 5 columns:
- ID
Patient ID
- Arm
Experimental arm ("Arm A", "Arm B")
- visit
Visit (character, "Cycle 1" to "Cycle 9")
- visit_nr
Visit number (numeric, 1 to 9)
- hb
Hemoglobin value (g/L)
Source
SAKK
Line plot of a summary statistic over time, by group
Description
Generates line plots of a central-tendency statistic over time for one or multiple sub-groups, optionally with a dispersion band (ribbon or whiskers) and a table of patient numbers beneath the horizontal axis.
Usage
lineplotSCI(
data,
var,
order,
group = NULL,
visit = NULL,
n_order = NULL,
group_names = NULL,
group_names_short = NULL,
stat = c("median", "mean", "geomean"),
interval = c("iqr", "range", "ci", "sd", "se", "gsd", "none"),
interval_type = c("whiskers", "ribbon"),
alpha = 0.05,
dodge = 0,
connect = TRUE,
connect_shade = 0.15,
main = "",
xlab = "Time",
ylab = "Variable",
xlim = NULL,
ylim = NULL,
y_ticks = NULL,
col = NULL,
cex_lab = 1,
cex_axis = 1,
cex_n_patients = 0.7,
risk_table = FALSE,
missing_nr = 0,
rotate_labels = FALSE,
mar_custom = NULL,
xlab_line = NULL,
ylab_line = 3,
xlab_position = NULL,
lines = NULL,
lty = 1,
col_lines = "grey",
legend_position = "topright",
legend_title = NULL,
legend_offset = c(0, 0),
legend_cex = 1,
legend_bty = "n",
stat_footnote = FALSE,
...
)
Arguments
data |
A data frame or tibble containing the data to be plotted. |
var |
Name of the column in |
order |
Name of the column in |
group |
Name of the column in |
visit |
Descriptive labels for the time points. Either the name of a
column in |
n_order |
A numeric value indicating the number of tick positions on the
x-axis. Default is |
group_names |
A character vector containing the names of the groups
to be displayed in the legend. The order must match |
group_names_short |
A character vector containing short names or abbreviations
for the groups, to be displayed below the x-axis near the patient counts.
Optional. Defaults to |
stat |
The summary statistic plotted as the point estimate: |
interval |
The quantity spanned by the error band around the point
estimate. One of |
interval_type |
The style in which the error band is drawn. Either
|
alpha |
The two-sided significance level used when |
dodge |
A numeric value giving the total horizontal offset applied
across groups, in x-axis units, so that overlapping error bars remain
readable. Default is |
connect |
A logical toggle switch controlling whether the point estimates
within a group are joined by a line. Default is |
connect_shade |
A numeric value between |
main |
Title of the plot. Defaults to |
xlab |
A label for the x-axis. Default is |
ylab |
A label for the y-axis. Default is |
xlim |
The x-axis limits of the plot as a numeric vector of length 2.
Default is |
ylim |
The y-axis limits of the plot as a numeric vector of length 2.
Default is |
y_ticks |
A numeric vector specifying the explicit tick positions on the
y-axis. Default is |
col |
A character vector of hex colors or color names to use for the
groups. Recycled if shorter than the number of groups. Default is |
cex_lab |
A numeric value specifying the font size of the main axis labels. Default is |
cex_axis |
A numeric value specifying the font size of the axis tick marks. Default is |
cex_n_patients |
A numeric value specifying the font size of the sample size
labels and numbers displayed beneath the horizontal axis. Default is |
risk_table |
A logical toggle switch enabling the table of patient numbers
(non-missing observations of |
missing_nr |
A numeric or character value indicating how zero-count patient
sizes on the x-axis should be displayed. Default is |
rotate_labels |
A logical toggle switch rotating the x-axis tick labels
by 90 degrees. Default is |
mar_custom |
A numeric vector indicating the plot margins to be used in
the form |
xlab_line |
A numeric value indicating the margin line offset for the x-axis label.
Default is |
ylab_line |
A numeric value indicating the margin line offset for the y-axis label.
Default is |
xlab_position |
Horizontal position coordinate adjustment for the sample size
group headers down the left-hand margin. Default is |
lines |
A numeric vector indicating the vertical coordinates where horizontal reference lines will be plotted. Optional. |
lty |
A numeric vector of length 1 or of the same length as |
col_lines |
A character vector of length 1 or of the same length as
|
legend_position |
Position of the legend box. Options include standard base R
keywords (e.g., |
legend_title |
Title of the legend box. Default is |
legend_offset |
A numeric vector of length 2 specifying an |
legend_cex |
A numeric value specifying the font and element scaling size
inside the legend box. Default is |
legend_bty |
The type of box border to be drawn around the legend.
Allowed values are |
stat_footnote |
Show what the plot displays as a footnote in the
bottom-right corner, beneath the x-axis title: |
... |
Further graphical parameters passed on to |
Value
Invisibly, a list with the group-by-time matrices centre, lower,
upper (both all-NA when interval is "none") and n, the number of
non-missing observations per cell.
Draw a line plot from pre-computed group-by-time summaries
Description
Drawing back end shared by lineplotSCI(), which summarises raw data, and
plotByVisit(), which reads the numbers off a summaryByVisit() table.
Usage
lineplot_draw(
centre,
lower,
upper,
obs,
xs,
at_x = xs,
visit = as.character(at_x),
band = any(!is.na(lower)),
interval_type = "whiskers",
group_names = NULL,
group_names_short = NULL,
dodge = 0,
connect = TRUE,
connect_shade = 0.15,
main = "",
xlab = "Time",
ylab = "Variable",
xlim = NULL,
ylim = NULL,
y_ticks = NULL,
col = NULL,
cex_lab = 1,
cex_axis = 1,
cex_n_patients = 0.7,
risk_table = FALSE,
missing_nr = 0,
rotate_labels = FALSE,
mar_custom = NULL,
xlab_line = NULL,
ylab_line = 3,
xlab_position = NULL,
lines = NULL,
lty = 1,
col_lines = "grey",
legend_position = "topright",
legend_title = NULL,
legend_offset = c(0, 0),
legend_cex = 1,
legend_bty = "n",
stat_footnote = NULL,
...
)
Arguments
centre, lower, upper |
Numeric group-by-time matrices with the point
estimate and the interval bounds ( |
obs |
Integer group-by-time matrix of non-missing observations. |
xs |
The x coordinates of the columns of |
at_x |
The tick positions on the x-axis. |
visit |
Descriptive labels for the time points. Either the name of a
column in |
band |
Logical; whether an error band is drawn at all. |
interval_type |
The style in which the error band is drawn. Either
|
group_names |
A character vector containing the names of the groups
to be displayed in the legend. The order must match |
group_names_short |
A character vector containing short names or abbreviations
for the groups, to be displayed below the x-axis near the patient counts.
Optional. Defaults to |
dodge |
A numeric value giving the total horizontal offset applied
across groups, in x-axis units, so that overlapping error bars remain
readable. Default is |
connect |
A logical toggle switch controlling whether the point estimates
within a group are joined by a line. Default is |
connect_shade |
A numeric value between |
main |
Title of the plot. Defaults to |
xlab |
A label for the x-axis. Default is |
ylab |
A label for the y-axis. Default is |
xlim |
The x-axis limits of the plot as a numeric vector of length 2.
Default is |
ylim |
The y-axis limits of the plot as a numeric vector of length 2.
Default is |
y_ticks |
A numeric vector specifying the explicit tick positions on the
y-axis. Default is |
col |
A character vector of hex colors or color names to use for the
groups. Recycled if shorter than the number of groups. Default is |
cex_lab |
A numeric value specifying the font size of the main axis labels. Default is |
cex_axis |
A numeric value specifying the font size of the axis tick marks. Default is |
cex_n_patients |
A numeric value specifying the font size of the sample size
labels and numbers displayed beneath the horizontal axis. Default is |
risk_table |
A logical toggle switch enabling the table of patient numbers
(non-missing observations of |
missing_nr |
A numeric or character value indicating how zero-count patient
sizes on the x-axis should be displayed. Default is |
rotate_labels |
A logical toggle switch rotating the x-axis tick labels
by 90 degrees. Default is |
mar_custom |
A numeric vector indicating the plot margins to be used in
the form |
xlab_line |
A numeric value indicating the margin line offset for the x-axis label.
Default is |
ylab_line |
A numeric value indicating the margin line offset for the y-axis label.
Default is |
xlab_position |
Horizontal position coordinate adjustment for the sample size
group headers down the left-hand margin. Default is |
lines |
A numeric vector indicating the vertical coordinates where horizontal reference lines will be plotted. Optional. |
lty |
A numeric vector of length 1 or of the same length as |
col_lines |
A character vector of length 1 or of the same length as
|
legend_position |
Position of the legend box. Options include standard base R
keywords (e.g., |
legend_title |
Title of the legend box. Default is |
legend_offset |
A numeric vector of length 2 specifying an |
legend_cex |
A numeric value specifying the font and element scaling size
inside the legend box. Default is |
legend_bty |
The type of box border to be drawn around the legend.
Allowed values are |
stat_footnote |
The text of the footnote in the bottom-right corner,
or |
... |
Further graphical parameters passed on to |
Value
Invisibly, a list with centre, lower, upper and n.
Natural ordering of levels for character variables
Description
Values starting with a number are sorted numerically by that number (e.g. "3" < "10", "2 doses" < "10 doses") and come first. A leading comparison operator is taken into account: "<10%" comes just before "10%", ">90%" just after "90%" (also "<=", ">=", and the symbols for these). All other values follow alphabetically, with embedded numbers compared numerically ("Arm 2" < "Arm 10"). NA is not a level.
Usage
natural_levels(x)
Arguments
x |
A character vector. |
Value
Character vector of levels in natural order.
Plot a summaryByVisit table
Description
Plots one variable of a table produced by summaryByVisit() over the
visits, using the numbers printed in the table rather than the raw data.
Continuous variables are drawn as a line plot of the point estimate with
its interval (see lineplotSCI()), categorical variables as stacked bars
(see stackedbarplotSCI()).
Usage
plotByVisit(
tbl,
var = NULL,
stat_cont = NULL,
missing = FALSE,
missing_text = "Missing",
...
)
Arguments
tbl |
A table returned by |
var |
The variable to be plotted, given as its label in the table (the
bold header row, e.g. |
stat_cont |
The statistic of continuous variables, as passed to
|
missing |
A logical toggle switch adding the missing-value rows of a
categorical variable as a segment of their own. Default is |
missing_text |
The label of the missing-value rows in the table, as
passed to |
... |
Further arguments controlling the appearance of the plot, as
documented in |
Details
The statistic of continuous variables is read from the table footnote and determines the error bars:
-
"median_range": median with whiskers from minimum to maximum; -
"median_IQR": median with whiskers from the first to the third quartile; -
"mean_sd"/"mean_se": mean +/- one standard deviation / standard error; -
"geomMean_sd": geometric mean divided and multiplied by the geometric standard deviation.
Since the numbers are read from the printed table, they carry its rounding
(digits_cont / digits_cat). Visits appear on the x-axis in the order
of the table rows.
Value
Invisibly, a list with
-
type:"continuous"or"categorical"; -
summary: the rows oftidySummaryByVisit()belonging tovar; for continuous variables, the group-by-visit matrices
centre,lower,upperandn;for categorical variables, the arrays
countsandpercentindexed by level, group and visit, and the group-by-visit matrixnof denominators.
Examples
library(summarySCI)
data("hemoglobin_data")
hb <- subset(hemoglobin_data, visit_nr <= 3) # first 3 cycles, to keep it short
attr(hb$hb, "label") <- "Hemoglobin" # subset() drops the label
tbl <- summaryByVisit(hb, vars = "hb",
group = "Arm", visit = "visit", stat_cont = "median_IQR",
as_flex_table = FALSE)
plotByVisit(tbl, var = "Hemoglobin", risk_table = TRUE)
# a categorical variable
hb$hb_cat <- cut(hb$hb, c(-Inf, 120, 140, Inf),
labels = c("< 120", "120-140", "> 140"))
tbl <- summaryByVisit(hb, vars = c("hb", "hb_cat"),
group = "Arm", visit = "visit", stat_cont = "median_IQR",
as_flex_table = FALSE)
plotByVisit(tbl, var = "hb_cat", legend_title = "Hemoglobin")
One row of patient numbers beneath the x-axis
Description
Draws the numbers n at the x positions at on margin line line, zero
counts shown as missing_nr, and optionally the row label "# <label>"
left of the plot, as in boxplotSCI().
Usage
risk_row(n, line, at, label = NULL, label_at = NULL, cex = 0.7, missing_nr = 0)
Arguments
n |
Numbers of patients. |
line |
Margin line of the row. |
at |
x positions of the numbers. |
label |
Group label of the row, or |
label_at |
x position of the right end of the label. |
cex |
Font size. |
missing_nr |
Shown instead of zero counts. |
Save a plot to a file
Description
Draws a plot of summarizeSCI() into a file. The format follows the file
extension: .png, .jpeg/.jpg, .tiff, .pdf or .svg.
Usage
save_plot(x, file, width = 8, height = 5, res = 300)
Arguments
x |
A |
file |
Path of the file to write. |
width, height |
Size of the plot in inches. Default is 8 by 5. |
res |
Resolution in dots per inch, for the pixel formats. Default is 300. |
Value
The path of the file, invisibly.
Save plots to files
Description
Writes the plots of a summarizeSCI() or summarizeByVisitSCI() result,
or a single plot such as res$plots$hb, each into its own file.
Usage
save_plots(
x,
file_name = NULL,
file_path = ".",
format = "png",
width = 8,
height = 5,
res = 300
)
Arguments
x |
The result of |
file_name |
Name(s) of the files, without extension. Either one name
per plot, or a single name that prefixes the variable names when |
file_path |
Folder to write the files into. Created if it does not exist. Default is the working directory. |
format |
File format: |
width, height |
Size of the plot in inches. Default is 8 by 5. |
res |
Resolution in dots per inch, for the pixel formats. Default is 300. |
Value
The paths of the files, invisibly.
Examples
## Not run:
save_plots(res) # hb.png, hb_cat.png
save_plots(res, file_name = "fig", file_path = "figures", format = "pdf")
save_plots(res$plots$hb, file_name = "hemoglobin") # hemoglobin.png
## End(Not run)
Save a flextable to a Word document
Description
What summaryTable(), summaryByVisit() and the wrappers do with
word_output = TRUE.
Usage
save_word(ft, file_path)
Arguments
ft |
A flextable. |
file_path |
Path of the |
Value
file_path, invisibly.
Layout of the plots
Description
Margins, lines of the patient numbers and of the x-axis title shared by
boxplotSCI(), lineplotSCI() and stackedbarplotSCI(), so that plots used
together line up. The blueprint is the layout of boxplotSCI().
Usage
sci_layout(n_time, n_groups, risk_table, offset = 0, footnote = FALSE)
Arguments
n_time |
Number of time points; |
n_groups |
Number of groups. |
risk_table |
Logical. Are patient numbers drawn beneath the x-axis? |
offset |
Lines taken by extra labels beneath the x-axis (e.g. group labels under bars, or rotated labels), by which the numbers and the x-axis title move down. |
footnote |
Logical. Is a footnote on the statistic drawn beneath the x-axis title? It adds the same space to every plot type. |
Value
A list with mar (for par(mar = )), rows (margin lines of the
rows of patient numbers, one per group over time, one for a single time
point), xlab_line and note_line (the line of the footnote).
SCI color palette
Description
The default colors of all plotting functions of the package.
Usage
sci_palette(n, lines = FALSE, bars = FALSE)
Arguments
n |
Number of colors. |
lines |
Logical. If |
bars |
Logical. If |
Value
A character vector of n hex colors, light to dark.
Plot objects
Description
The plotting functions of the package draw with base R graphics, which
produce no object to keep. The wrappers summarizeSCI() therefore store
each plot as a sci_plot: the instructions to draw it, together with the
numbers it shows. Printing a sci_plot draws it on the current device, and
save_plot() draws it into a file of the requested size, so that the
layout is always worked out for the size it is drawn at.
Usage
## S3 method for class 'sci_plot'
print(x, ...)
## S3 method for class 'sci_plot'
plot(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
print() and plot() return x invisibly.
Standard error
Description
This function return the standard error
Usage
se(x)
Arguments
x |
Numeric vector |
Value
standard error
Draw a stacked barplot from pre-computed counts
Description
Drawing back end shared by stackedbarplotSCI(), which counts raw data, and
plotByVisit(), which reads the counts off a summaryByVisit() table.
Usage
stackedbar_draw(
counts,
n,
visit = dimnames(counts)[[3]],
group_names = NULL,
group_names_short = NULL,
scale = "percent",
main = "",
xlab = NULL,
ylab = NULL,
ylim = NULL,
y_ticks = NULL,
col = NULL,
greyscale = FALSE,
percent_labels = TRUE,
col_percent = NULL,
cex_percent = NULL,
digits = 0,
bar_width = NULL,
cex_lab = 1,
cex_axis = 1,
cex_n_patients = 0.7,
cex_groups = NULL,
missing_seg = NULL,
risk_table = FALSE,
missing_nr = 0,
rotate_labels = FALSE,
mar_custom = NULL,
xlab_line = NULL,
ylab_line = 3,
xlab_position = NULL,
legend_position = "top",
legend_title = NULL,
legend_offset = c(0, 0),
legend_cex = 1,
legend_bty = "n",
stat_footnote = NULL,
...
)
Arguments
counts |
Numeric array of counts indexed by segment, group and time point, with dimnames. |
n |
Numeric group-by-time matrix of denominators for the percentages. |
visit |
Character vector of labels for the time points, one per
column of the third dimension of |
group_names |
A character vector containing the names of the groups
to be displayed on the x-axis. The order must match |
group_names_short |
A character vector containing short names or
abbreviations for the groups, displayed beneath the bars and in the table of
patient numbers. Optional. Defaults to |
scale |
The quantity on the y-axis. Either |
main |
Title of the plot. Defaults to |
xlab |
A label for the x-axis. Default is |
ylab |
A label for the y-axis. Default is |
ylim |
The y-axis limits of the plot as a numeric vector of length 2.
Default is |
y_ticks |
A numeric vector specifying the explicit tick positions on the
y-axis. Default is |
col |
A character vector of hex colors or color names to use for the
stacked segments, bottom to top. Recycled if shorter than the number of
segments. The missing-value segment (see |
greyscale |
A logical toggle switch replacing the color palette by a
sequential grey ramp, for print or black-and-white reproduction. Default is
|
percent_labels |
A logical toggle switch enabling the percentage labels
printed inside the segments. Default is |
col_percent |
A character value giving the color of the percentage
labels. Default is |
cex_percent |
A numeric value specifying the font size of the percentage
labels. Default is |
digits |
A numeric value indicating the number of decimal places shown
in the percentage labels. Default is |
bar_width |
A numeric value giving the width of each bar in x-axis
units. Default is |
cex_lab |
A numeric value specifying the font size of the main axis labels. Default is |
cex_axis |
A numeric value specifying the font size of the axis tick marks. Default is |
cex_n_patients |
A numeric value specifying the font size of the table
of patient numbers. Default is |
cex_groups |
A numeric value specifying the font size of the group
labels beneath the bars (several groups over time). Default is |
missing_seg |
Index of the segment holding the missing values, drawn
hatched instead of coloured. Default is |
risk_table |
A logical toggle switch enabling the table of patient
numbers (the denominator of each bar) beneath the x-axis. Default is |
missing_nr |
A numeric or character value indicating how zero-count patient
sizes on the x-axis should be displayed. Default is |
rotate_labels |
A logical toggle switch rotating the x-axis tick labels
by 90 degrees. Default is |
mar_custom |
A numeric vector indicating the plot margins to be used in
the form |
xlab_line |
A numeric value indicating the margin line offset for the x-axis label.
Default is |
ylab_line |
A numeric value indicating the margin line offset for the y-axis label.
Default is |
xlab_position |
Horizontal position of the row labels of the table of
patient numbers. Default is |
legend_position |
Position of the legend box. |
legend_title |
Title of the legend box. Default is |
legend_offset |
A numeric vector of length 2 specifying an |
legend_cex |
A numeric value specifying the font and element scaling size
inside the legend box. Default is |
legend_bty |
The type of box border to be drawn around the legend.
Allowed values are |
stat_footnote |
The text of the footnote in the bottom-right corner,
or |
... |
Further graphical parameters passed on to |
Value
Invisibly, a list with counts, n and percent.
Stacked barplot over time
Description
Generates stacked barplots of a categorical variable over time for one or
multiple sub-groups. Each bar shows the distribution of the levels of var
at one time point in one group, optionally with the percentages printed
inside the segments and a table of patient numbers beneath the horizontal
axis.
Usage
stackedbarplotSCI(
data,
var,
order = NULL,
visit = NULL,
group = NULL,
id = NULL,
group_names = NULL,
group_names_short = NULL,
level_names = NULL,
scale = c("percent", "count"),
missing = FALSE,
missing_text = "Missing",
main = "",
xlab = NULL,
ylab = NULL,
ylim = NULL,
y_ticks = NULL,
col = NULL,
greyscale = FALSE,
percent_labels = TRUE,
col_percent = NULL,
cex_percent = NULL,
digits = 0,
bar_width = NULL,
cex_lab = 1,
cex_axis = 1,
cex_n_patients = 0.7,
cex_groups = NULL,
risk_table = FALSE,
missing_nr = 0,
rotate_labels = FALSE,
mar_custom = NULL,
xlab_line = NULL,
ylab_line = 3,
xlab_position = NULL,
legend_position = "top",
legend_title = NULL,
legend_offset = c(0, 0),
legend_cex = 1,
legend_bty = "n",
stat_footnote = FALSE,
...
)
Arguments
data |
A data frame or tibble containing the data to be plotted. |
var |
Name of the column(s) in |
order |
Name of the column in |
visit |
Name of the column in |
group |
Name of the column in |
id |
Name of the column in |
group_names |
A character vector containing the names of the groups
to be displayed on the x-axis. The order must match |
group_names_short |
A character vector containing short names or
abbreviations for the groups, displayed beneath the bars and in the table of
patient numbers. Optional. Defaults to |
level_names |
A character vector containing the names of the stacked
segments to be displayed in the legend. The order must match the levels of
|
scale |
The quantity on the y-axis. Either |
missing |
A logical toggle switch adding missing values of |
missing_text |
Legend text for the missing-value segment. Default is
|
main |
Title of the plot. Defaults to |
xlab |
A label for the x-axis. Default is |
ylab |
A label for the y-axis. Default is |
ylim |
The y-axis limits of the plot as a numeric vector of length 2.
Default is |
y_ticks |
A numeric vector specifying the explicit tick positions on the
y-axis. Default is |
col |
A character vector of hex colors or color names to use for the
stacked segments, bottom to top. Recycled if shorter than the number of
segments. The missing-value segment (see |
greyscale |
A logical toggle switch replacing the color palette by a
sequential grey ramp, for print or black-and-white reproduction. Default is
|
percent_labels |
A logical toggle switch enabling the percentage labels
printed inside the segments. Default is |
col_percent |
A character value giving the color of the percentage
labels. Default is |
cex_percent |
A numeric value specifying the font size of the percentage
labels. Default is |
digits |
A numeric value indicating the number of decimal places shown
in the percentage labels. Default is |
bar_width |
A numeric value giving the width of each bar in x-axis
units. Default is |
cex_lab |
A numeric value specifying the font size of the main axis labels. Default is |
cex_axis |
A numeric value specifying the font size of the axis tick marks. Default is |
cex_n_patients |
A numeric value specifying the font size of the table
of patient numbers. Default is |
cex_groups |
A numeric value specifying the font size of the group
labels beneath the bars (several groups over time). Default is |
risk_table |
A logical toggle switch enabling the table of patient
numbers (the denominator of each bar) beneath the x-axis. Default is |
missing_nr |
A numeric or character value indicating how zero-count patient
sizes on the x-axis should be displayed. Default is |
rotate_labels |
A logical toggle switch rotating the x-axis tick labels
by 90 degrees. Default is |
mar_custom |
A numeric vector indicating the plot margins to be used in
the form |
xlab_line |
A numeric value indicating the margin line offset for the x-axis label.
Default is |
ylab_line |
A numeric value indicating the margin line offset for the y-axis label.
Default is |
xlab_position |
Horizontal position of the row labels of the table of
patient numbers. Default is |
legend_position |
Position of the legend box. |
legend_title |
Title of the legend box. Default is |
legend_offset |
A numeric vector of length 2 specifying an |
legend_cex |
A numeric value specifying the font and element scaling size
inside the legend box. Default is |
legend_bty |
The type of box border to be drawn around the legend.
Allowed values are |
stat_footnote |
Show what the bars display as a footnote in the
bottom-right corner, beneath the x-axis title: |
... |
Further graphical parameters passed on to |
Details
Two layouts of the data are supported:
-
varnames one categorical column (long format): its levels are stacked, and percentages are relative to the number of non-missing observations in the bar (or all observations ifmissing = TRUE). -
varnames several columns coded"Yes"/"No"(wide format, e.g. one column per adverse event): each column becomes one segment holding the number of"Yes"answers, and percentages are relative to the number of patients in the bar (id, or rows ifidisNULL). Missing values count as"No". Since a patient may answer"Yes"to several columns, the segments can add up to more than 100%.
Value
Invisibly, a list with counts and percent, arrays indexed by
segment, group and time point, and n, the group-by-time matrix of
denominators.
Examples
library(summarySCI)
data("hemoglobin_data")
hemoglobin_data$hb_cat <- cut(hemoglobin_data$hb, c(-Inf, 120, 140, Inf),
labels = c("< 120", "120-140", "> 140"))
stackedbarplotSCI(data = hemoglobin_data,
var = hb_cat,
order = visit_nr,
visit = visit,
group = Arm,
group_names_short = c("A", "B"),
legend_title = "Hemoglobin",
risk_table = TRUE)
# Several Yes/No columns, one bar per arm
set.seed(14)
ae <- data.frame(id = 1:50,
arm = sample(c("Arm A", "Arm B"), 50, replace = TRUE),
fatigue = sample(c("Yes", "No"), 50, replace = TRUE),
nausea = sample(c("Yes", "No"), 50, replace = TRUE))
stackedbarplotSCI(ae, var = c("fatigue", "nausea"), group = arm, id = id,
scale = "count", legend_title = "Adverse events")
Summarize data by visit as a table and plots
Description
Produces the table of summaryByVisit() and one plot per variable (or
either of them alone, see type), the plots
over the visits: a line plot or boxplots (boxplotSCI()) for continuous
variables, and stacked barplots for categorical ones. The type of each plot
follows the type the variable has in the table.
Usage
summarizeByVisitSCI(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cont = "median_range",
stat_cat = "n_percent",
visit = "visit",
order = NULL,
visitgroup = NULL,
missing = TRUE,
missing_percent = TRUE,
missing_text = "Missing",
continuous_as_categorical = NULL,
type = c("both", "table", "plot"),
plot_cont = c("lineplot", "boxplot"),
plot_args = list(),
as_flex_table = TRUE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryByVisit_", format(Sys.Date(), "%Y%m%d"), ".docx"),
...
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the
variables in the table, either named by variable
(e.g. |
stat_cont |
Summary statistic to display for continuous variables. Options include "median_IQR", "median_range" (default), "mean_sd", "mean_se" and "geomMean_sd". |
stat_cat |
Summary statistic to display for categorical variables. Options include "n", "n_N" and "n_percent" (default). |
visit |
Name of the stratum for which summary statistics are
displayed by line. Typically, this would be |
order |
A numerical variable defining the visit order. If NULL
(default), visits are sorted naturally (e.g. "Visit 2" before "Visit 10");
if |
visitgroup |
A grouping variable for the stratum for which summary statistics are displayed by line. Must be an ordered factor. Typically, this would be a visit group such as e.g., baseline, follow-up etc. |
missing |
Logical. If TRUE (default), the missing values are shown (only for categorical variables). |
missing_percent |
Indicates whether percentages for missings are shown (TRUE, default) or not (FALSE) for categorical variables. If "both", then both options are displayed next to each other. |
missing_text |
String indicating text shown on missing row. Default to "Missing". |
continuous_as_categorical |
A subset (vector) of continuous vars to be treated as categrical. Default is NULL. |
type |
What to produce: |
plot_cont |
The plot for continuous variables: |
plot_args |
A named list of further arguments for the plotting
functions, e.g. |
as_flex_table |
Logical. If TRUE (default) the gtsummary object is converted to a flextable object. Useful when rendering to Word. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
... |
Further arguments passed on to |
Details
The line plots and stacked bars are drawn from the numbers printed in the
table, as plotByVisit() does, so that they show exactly what the table
shows (with its rounding):
-
stat_contsets what the line plot shows:"median_range"the median with minimum and maximum,"median_IQR"the median with the quartiles,"mean_sd"/"mean_se"the mean +/- one standard deviation / standard error, and"geomMean_sd"the geometric mean divided and multiplied by the geometric standard deviation; the variable labels become the axis or legend titles, the column headers the group names, and the N columns the numbers of the risk table;
-
missing/missing_percentdecide whether missing values form a segment of their own (as they are counted in the table's percentages), andstat_cat = "n"shows counts instead of percentages; -
continuous_as_categoricalvariables are plotted as stacked bars, and withoverall = TRUEthe overall column is plotted as one more group.
Boxplots show more than the table holds, and are drawn from the data: from
the rows the table summarizes, with the box at the quartiles of the table
(see boxplotSCI()).
The visits appear in the order of the table. If order is given, its values
also set the spacing of the visits in the line plots.
Value
An object of class summarizeByVisitSCI (and summarizeSCI), a
list with table and plots; see summarizeSCI().
Examples
library(summarySCI)
data("hemoglobin_data")
hb <- subset(hemoglobin_data, visit_nr <= 2) # first 2 cycles, to keep it short
res <- summarizeByVisitSCI(hb, vars = "hb",
group = "Arm", visit = "visit", order = "visit_nr",
stat_cont = "median_IQR")
res$plots$hb
# a categorical variable
hb$hb_cat <- cut(hb$hb, c(-Inf, 120, 140, Inf),
labels = c("< 120", "120-140", "> 140"))
res <- summarizeByVisitSCI(hb, vars = c("hb", "hb_cat"),
group = "Arm", visit = "visit", order = "visit_nr",
stat_cont = "median_IQR")
res$plots$hb_cat
Summarize data as a table and plots
Description
Produces the summary table of summaryTable() and one plot per variable,
or either of them alone (see type): a boxplot for continuous variables
(boxplotSCI()) and a
stacked barplot for categorical and dichotomous ones
(stackedbarplotSCI()). The type of each plot follows the type the
variable has in the table, so that table and plots always agree.
Usage
summarizeSCI(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cont = "median_range",
stat_cat = "n_percent",
missing = TRUE,
missing_percent = TRUE,
missing_text = "Missing",
type = c("both", "table", "plot"),
plot_args = list(),
as_flex_table = TRUE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryTable_", format(Sys.Date(), "%Y%m%d"), ".docx"),
...
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the variables in the table. If NULL, labels are automatically taken from the dataset. If no label present, the variable name is taken. |
stat_cont |
Summary statistic to display for continuous variables. Options
include "median_IQR", "median_range" (default), "mean_sd", "mean_se" and
"geomMean_sd".
"geomMean_sd" shows the geometric mean with the geometric standard
deviation, |
stat_cat |
Summary statistic to display for categorical variables. Options include "n_percent" (default) and "n", and "n_N". |
missing |
Logical. If TRUE (default), the missing values are shown. |
missing_percent |
Indicates whether percentages for missings are shown (TRUE, default) or not (FALSE) for categorical variables. If "both", then both options are displayed next to each other. |
missing_text |
String indicating text shown on missing row. Default to "Missing". |
type |
What to produce: |
plot_args |
A named list of further arguments for the plotting
functions, e.g. |
as_flex_table |
Logical. If TRUE (default) the gtsummary object is converted to a flextable object. Useful when rendering to Word. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
... |
Further arguments passed on to |
Details
The plots are drawn from the same rows as the table, and the box of the
boxplot spans the quartiles as the table computes them (see boxplotSCI()).
The settings of the table carry over to the plots: the variable labels
become the axis or legend titles, missing / missing_percent decide
whether missing values form a segment of their own (as they are counted in
the table's percentages), and stat_cat = "n" shows counts instead of
percentages. Options that only concern the plots go into plot_args.
Value
An object of class summarizeSCI, a list with
-
table: the table, a flextable or (withas_flex_table = FALSE) a gtsummary object;NULLwithtype = "plot". Withword_output = TRUEit is also saved tofile_path, assummaryTable()does; -
plots: a named list with one plot per variable, e.g.res$plots$hb; empty withtype = "table". Printing a plot draws it;save_plots()writes them to files.
Printing the result shows the table and lists the plots.
Examples
library(summarySCI)
data("hemoglobin_data")
d <- hemoglobin_data[hemoglobin_data$visit_nr == 2, ]
d$hb_cat <- cut(d$hb, c(-Inf, 120, 140, Inf),
labels = c("< 120", "120-140", "> 140"))
res <- summarizeSCI(d, vars = c("hb", "hb_cat"), group = "Arm")
res$table
res$plots$hb
res$plots$hb_cat
# the plots alone
plots <- summarizeSCI(d, vars = c("hb", "hb_cat"), group = "Arm",
type = "plot")$plots
## Not run:
save_plots(res, file_name = "fig", file_path = "figures")
## End(Not run)
Creates publication-ready summary tables for data grouped, by visit
Description
Creates publication-ready summary tables for data grouped, by visit
Usage
summaryByVisit(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cont = "median_range",
stat_cat = "n_percent",
visit = "visit",
order = NULL,
visitgroup = NULL,
digits_cont = 1,
digits_cat = 0,
missing_percent = TRUE,
missing = TRUE,
missing_text = "Missing",
add_n = TRUE,
overall = FALSE,
continuous_as_categorical = NULL,
as_flex_table = TRUE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryByVisit_", format(Sys.Date(), "%Y%m%d"), ".docx")
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the
variables in the table, either named by variable
(e.g. |
stat_cont |
Summary statistic to display for continuous variables. Options include "median_IQR", "median_range" (default), "mean_sd", "mean_se" and "geomMean_sd". |
stat_cat |
Summary statistic to display for categorical variables. Options include "n", "n_N" and "n_percent" (default). |
visit |
Name of the stratum for which summary statistics are
displayed by line. Typically, this would be |
order |
A numerical variable defining the visit order. If NULL
(default), visits are sorted naturally (e.g. "Visit 2" before "Visit 10");
if |
visitgroup |
A grouping variable for the stratum for which summary statistics are displayed by line. Must be an ordered factor. Typically, this would be a visit group such as e.g., baseline, follow-up etc. |
digits_cont |
Digits for summary statistics and CI of continuous variables. Default to 1. |
digits_cat |
Digits for summary statistics and CI of categorical variables. Default to 0. |
missing_percent |
Indicates whether percentages for missings are shown (TRUE, default) or not (FALSE) for categorical variables. If "both", then both options are displayed next to each other. |
missing |
Logical. If TRUE (default), the missing values are shown (only for categorical variables). |
missing_text |
String indicating text shown on missing row. Default to "Missing". |
add_n |
Logical. If TRUE, an additional column with the total number of non-missing observations for each variable is added. Default to TRUE. |
overall |
Logical. If TRUE, an additional column with the total is added to the table. Ignored, if no groups are defined. Default to FALSE. |
continuous_as_categorical |
A subset (vector) of continuous vars to be treated as categrical. Default is NULL. |
as_flex_table |
Logical. If TRUE (default) the gtsummary object is converted to a flextable object. Useful when rendering to Word. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
Value
A table of class "flextable" or c("tbl_strata_nested_stack", "tbl_stack", "gtsummary").
Optionally returns a .docx file in the specified folder.
Examples
data("hemoglobin_data")
hb <- subset(hemoglobin_data, visit_nr <= 3) # first 3 cycles, to keep it short
# Hemoglobin by visit and arm, with an overall column
summaryByVisit(data = hb, vars = "hb", visit = "visit",
group = "Arm", overall = TRUE,
labels = list(hb = "Hemoglobin (g/L)"))
Creates publication-ready summary tables for categorical data grouped, by visit
Description
Creates publication-ready summary tables for categorical data grouped, by visit
Usage
summaryByVisitCategorical(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cat = "n_percent",
visit = "visit",
order = NULL,
visitgroup = NULL,
digits_cat = 0,
missing_percent = TRUE,
missing = TRUE,
missing_text = "Missing",
add_n = TRUE,
overall = FALSE,
as_flex_table = FALSE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryByVisit_", format(Sys.Date(), "%Y%m%d"), ".docx")
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Continuous variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the variables in the table. If NULL, labels are automatically taken from the dataset. If no label present, the variable name is taken. |
stat_cat |
Summary statistic to display for categorical variables. Options include "n", "n_N" and "n_percent" (default). |
visit |
Name of the stratum for which summary statistics are
displayed by line. Typically, this would be |
order |
A numerical variable defining the visit order. |
visitgroup |
A grouping variable for the stratum for which summary statistics are displayed by line. Must be an ordered factor. Typically, this would be a visit group such as e.g., baseline, follow-up etc. |
digits_cat |
Digits for summary statistics of categorical variables. Default to 0. |
missing_percent |
Indicates whether percentages for missings are shown (TRUE, default) or not (FALSE) for categorical variables. If "both", then both options are displayed next to each other. |
missing |
Logical. If TRUE (default), the missing values are shown. |
missing_text |
String indicating text shown on missing row. Default to "Missing". |
add_n |
Logical. If TRUE, an additional column with the total number of non-missing observations for each variable is added. Default to TRUE. |
overall |
Logical. If TRUE, an additional column with the total is added to the table. Ignored, if no groups are defined. Default to FALSE. |
as_flex_table |
Logical. If TRUE, the gtsummary object is converted to a flextable object. Useful when rendering to Word. Default to FALSE. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
Value
A table of class "flextable" or c("tbl_strata_nested_stack", "tbl_stack", "gtsummary").
Optionally returns a .docx file in the specified folder.
Creates publication-ready summary tables for continuous data grouped, by visit
Description
Creates publication-ready summary tables for continuous data grouped, by visit
Usage
summaryByVisitContinuous(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cont = "median_range",
visit = "visit",
order = NULL,
visitgroup = NULL,
digits_cont = 1,
add_n = TRUE,
overall = FALSE,
as_flex_table = FALSE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryByVisit_", format(Sys.Date(), "%Y%m%d"), ".docx")
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Continuous variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the variables in the table. If NULL, labels are automatically taken from the dataset. If no label present, the variable name is taken. |
stat_cont |
Summary statistic to display for continuous variables.
Options include "median_IQR", "median_range" (default), "mean_sd",
"mean_se" and "geomMean_sd".
"geomMean_sd" shows the geometric mean with the geometric standard
deviation, |
visit |
Name of the stratum for which summary statistics are
displayed by line. Typically, this would be |
order |
A numerical variable defining the visit order. |
visitgroup |
A grouping variable for the stratum for which summary statistics are displayed by line. Must be an ordered factor. Typically, this would be a visit group such as e.g., baseline, follow-up etc. |
digits_cont |
Digits for summary statistics and CI of continuous variables. Default to 1. |
add_n |
Logical. If TRUE, an additional column with the total number of non-missing observations for each variable is added. Default to TRUE. |
overall |
Logical. If TRUE, an additional column with the total is added to the table. Ignored, if no groups are defined. Default to FALSE. |
as_flex_table |
Logical. If TRUE, the gtsummary object is converted to a flextable object. Useful when rendering to Word. Default to FALSE. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
Value
A table of class "flextable" or c("tbl_strata_nested_stack", "tbl_stack", "gtsummary").
Optionally returns a .docx file in the specified folder.
summaryLevels
Description
Collapses factor levels from multiple columns into one and creates summary table.
Usage
summaryLevels(
data,
vars = NULL,
group = NULL,
label = NULL,
levels = NULL,
stat_cat = "n_percent",
test = FALSE,
test_cat = "fisher.test",
ci = FALSE,
ci_cat = "clopper.pearson",
conf_level = 0.95,
digits_cat = 0,
overall = FALSE,
add_n = TRUE,
as_flex_table = TRUE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryLevels_", format(Sys.Date(), "%Y%m%d"), ".docx")
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
label |
A label for the new variable to be created. If no label present, the variable name is taken. |
levels |
= A vector containing the values indicating presence of
the factor level. Included by default are "1", "yes", "Yes".
All variables in |
stat_cat |
Summary statistic to display for categorical variables. Options include "n_percent" (default) and "n", and "n_N". |
test |
Logical. Indicates whether p-values are displayed (TRUE) or not (FALSE). Default to FALSE |
test_cat |
Test type used to calculated the p-value
for categorical variables. Only used if |
ci |
Logical. Indicates whether CI are displayed (TRUE) or not (FALSE). Default to FALSE. |
ci_cat |
Confidence interval method for categorical variables. Options include "clopper.pearson" (default), "wilson", "wilson.no.correct", "wald", "wald.no.correct", "agresti.coull" and "jeffreys". If NULL, no CI will be displayed. |
conf_level |
Numeric. Confidence level. Default to 0.95. |
digits_cat |
Numeric. Digits for summary statistics and CI of categorical variables. Default to 0. |
overall |
Logical. If TRUE, an additional column with the total is added at the end of the table. Default to FALSE. |
add_n |
Logical. If TRUE (default), a column with the number of patients is added before each group column (and before the Overall column). As missing values are treated as absent, N is the number of patients in each group. |
as_flex_table |
Logical. If TRUE (default) the gtsummary object is converted to a flextable object. Useful when rendering to Word. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
Value
A table of class "flextable" or c("tbl_stack", "gtsummary").
Optionally returns a .docx file in the specified folder.
Examples
# Site of progression: one column per site, more than one site possible
progression <- data.frame(
arm = rep(c("A", "B"), each = 5),
liver = c("absent", "present", "absent", "present", "absent",
"absent", "present", "absent", "present", "absent"),
lung = c("absent", "absent", "present", "absent", "absent",
"absent", "absent", "absent", "absent", "absent"),
brain = c("present", "absent", "present", "present", "present",
"present", "present", "present", "present", "present")
)
summaryLevels(data = progression,
vars = c("liver", "lung", "brain"),
label = "Site of progression",
levels = "present")
# By arm, with an overall column
summaryLevels(data = progression,
vars = c("liver", "lung", "brain"),
group = "arm",
overall = TRUE,
label = "Site of progression",
levels = "present")
Creates publication-ready summary tables
Description
Creates publication-ready summary tables based on the gtsummary package.
Usage
summaryTable(
data,
vars = NULL,
group = NULL,
labels = NULL,
stat_cont = "median_range",
stat_cat = "n_percent",
continuous_as = "continuous",
dichotomous_as = "dichotomous",
continuous_as_categorical = NULL,
dichotomous_as_categorical = NULL,
ref_level = NULL,
test = FALSE,
test_cont = NULL,
test_cat = "fisher.test",
ci = FALSE,
ci_cont = "wilcox.test",
ci_cat = "clopper.pearson",
conf_level = 0.95,
digits_cont = 1,
digits_cat = 0,
missing = TRUE,
missing_percent = TRUE,
missing_text = "Missing",
overall = FALSE,
add_n = TRUE,
as_flex_table = TRUE,
border = TRUE,
word_output = FALSE,
file_path = paste0("SummaryTable_", format(Sys.Date(), "%Y%m%d"), ".docx")
)
Arguments
data |
A data frame or tibble containing the data to be summarized. |
vars |
Variables to include in the summary table.
Need to be specified with quotes, e.g. |
group |
A single column from |
labels |
A list containing the labels that should be used for the variables in the table. If NULL, labels are automatically taken from the dataset. If no label present, the variable name is taken. |
stat_cont |
Summary statistic to display for continuous variables. Options
include "median_IQR", "median_range" (default), "mean_sd", "mean_se" and
"geomMean_sd".
"geomMean_sd" shows the geometric mean with the geometric standard
deviation, |
stat_cat |
Summary statistic to display for categorical variables. Options include "n_percent" (default) and "n", and "n_N". |
continuous_as |
Type for all the continuous variables. Can either be "continuous" (default) or "categorical". |
dichotomous_as |
Type for the dichotomous variables. Can either be
"categorical" (one row per level) or "dichotomous" (only
one row with reference level (see argument |
continuous_as_categorical |
A subset (vector) of continuous vars to be treated as categorical. Default is NULL. |
dichotomous_as_categorical |
A subset (vector) of dichotomous vars to be treated as categorical. Default is NULL. |
ref_level |
Specifies the reference level of a variable to display on a single row.
Default is the first appearing level. The syntax is as follows: |
test |
Logical. Indicates whether p-values are displayed (TRUE) or not (FALSE). Default to FALSE |
test_cont |
Test type used to calculate the p-value
for continuous variables. Only used if |
test_cat |
Test type used to calculated the p-value
for categorical variables. Only used if |
ci |
Logical. Indicates whether CI are displayed (TRUE) or not (FALSE). Default to FALSE. |
ci_cont |
Confidence interval method for continuous variables.
Only used if |
ci_cat |
Confidence interval method for categorical variables. Options include "clopper.pearson" (default) "wilson", "wilson.no.correct", "wald", "wald.no.correct", "agresti.coull" and "jeffreys". If NULL, no CI will be displayed. |
conf_level |
Numeric. Confidence level. Default to 0.95. |
digits_cont |
Numeric. Digits for summary statistics and CI of continuous variables. Default to 1. |
digits_cat |
Numeric. Digits for summary statistics and CI of categorical variables. Default to 0. |
missing |
Logical. If TRUE (default), the missing values are shown. |
missing_percent |
Indicates whether percentages for missings are shown (TRUE, default) or not (FALSE) for categorical variables. If "both", then both options are displayed next to each other. |
missing_text |
String indicating text shown on missing row. Default to "Missing". |
overall |
Logical. If TRUE, an additional column with the total is added to the table. Default to FALSE. |
add_n |
Logical. If TRUE (default), an additional column with the total number of non-missing observations for each variable is added. |
as_flex_table |
Logical. If TRUE (default) the gtsummary object is converted to a flextable object. Useful when rendering to Word. |
border |
Logical. If TRUE, a border will be drawn around the table. Only available if flex_table = TRUE. Default is TRUE. |
word_output |
Logical. If TRUE, the table is also saved in a word document. |
file_path |
Character string.
Specify the path of the Word document containing the table.
Only used when |
Details
Character variables (and a character group) are converted to
factors with natural level order: values starting with a number are sorted
numerically (e.g. "3", "10", "more than 10"), other values alphabetically
with embedded numbers compared numerically (e.g. "Arm 2" before "Arm 10").
To control the order fully, supply a factor with the desired levels.
Value
A table of class "flextable" or c("tbl_summary", "gtsummary").
Optionally returns a .docx file in the specified folder.
Examples
library(survival)
data("cancer")
summaryTable(data = cancer,vars = c("inst", "time","age", "ph.ecog"),
labels = list(inst = "Institution code",
time = "Time",
age = "Age",
ph.ecog = "ECOG score"))
Read the numbers off a summaryByVisit table
Description
Converts a table produced by summaryByVisit() into a data frame with one
row per variable, visit, group and (for categorical variables) level,
holding the parsed numbers. This is the parser behind plotByVisit().
Usage
tidySummaryByVisit(tbl, stat_cont = NULL)
Arguments
tbl |
A table returned by |
stat_cont |
The statistic of continuous variables, as passed to
|
Value
A data frame with columns variable (the label of the header row),
var_type, visitgroup, visit, visit_id (position of the visit within
the variable), group, level (NA for continuous variables), stat
(the cell as printed), n (the number of non-missing observations shown in
the table's N column), and the parsed numbers centre, lower, upper
(continuous) and count (categorical).
Convert a gtsummary table to a flextable
Description
The conversion summaryTable() applies when as_flex_table = TRUE: a
flextable fitted to the page width, with an outer border if requested.
Usage
to_flextable(tbl, border = TRUE)
Arguments
tbl |
A gtsummary table. |
border |
Logical. Draw a border around header and body. |
Value
A flextable.