Package 'blockr.viz'

Title: Chart and Table Blocks for 'blockr'
Description: Two blocks for 'blockr' boards. The chart block draws bar, histogram, waterfall, pie, treemap, box, point-range, scatter, line, area, band and timeline charts with 'ECharts', aggregating the rows where the chart type asks for it. The table block shows the rows, one row per group with a column per summary, or one row per statistic of each variable, as a table, a compact matrix or cards. A click on either filters the blocks downstream. Both download as 'Excel', a web page, an image or 'PowerPoint'.
Authors: Christoph Sax [aut, cre] (ORCID: <https://orcid.org/0000-0002-7192-7044>), ZumerLab [cph] (SnapDOM, bundled in inst/js/vendor/snapdom.js)
Maintainer: Christoph Sax <[email protected]>
License: GPL (>= 3)
Version: 0.3.0.9103
Built: 2026-11-19 08:17:37 UTC
Source: https://github.com/BristolMyersSquibb/blockr.viz

Help Index


Coerce a table object into an annotated data frame

Description

An annotated data frame is a plain data frame whose reserved .-columns describe a display table's structure and identity: .label (row stub), the ARD-named identity pairs ⁠.group<k>⁠ / ⁠.group<k>_level⁠ (row-grouping variable name / value) and .variable / .variable_level (leaf source variable / value; an NA level marks a stat row), their optional ⁠_label⁠ display companions, .indent (extra display depth) and .strong / .emph (emphasis). Two-level column spanners are encoded in the column name as Top||Leaf. The table-level attributes label (the title), subtitle and caption carry display text. Section headers are synthesized by the renderer from grouping-value runs and are never rows of the frame.

Usage

as_annotated_df(x, ...)

## S3 method for class 'data.frame'
as_annotated_df(x, ...)

## Default S3 method:
as_annotated_df(x, ...)

Arguments

x

A table-producing object that has an as_annotated_df method.

...

Passed on to methods.

Details

It is the format new_table_block() consumes and summary_table() produces. as_annotated_df() coerces a table-producing object (composer, gtsummary, gt, rtables, ...) into that data frame. Producer packages register one S3 method each. A data frame passes through untouched, so coercion is idempotent.

Value

An annotated data frame.

See Also

new_table_block(), summary_table()

Examples

tbl <- summary_table(iris, vars = "Species")
as_annotated_df(tbl)

Coerce a table object into a plain data frame

Description

as_annotated_df() followed by dropping the reserved .-annotation columns (.label, .indent, .strong, .emph, .fmt, .digits, ⁠.variable*⁠, ⁠.group<k>*⁠). Other dot-prefixed columns pass through.

Usage

as_plain_df(x, ...)

Arguments

x

A data frame or an object with an as_annotated_df() method.

...

Passed on to as_annotated_df().

Value

A data frame without the reserved annotation columns.

See Also

as_annotated_df(), new_chart_block(), new_table_block()

Examples

tbl <- summary_table(iris, vars = "Sepal.Length", by = "Species")
as_plain_df(tbl)

The board's drill destination, found by class

Description

What ctrl_target = "auto" resolves to: the one blockr.dm::new_drill_filter_block() on the board or, on a board without one, the one value filter block.

Usage

ctrl_auto_target(session = shiny::getDefaultReactiveDomain())

Arguments

session

Shiny session (defaults to the current reactive domain).

Details

Two or more candidates resolve to nothing, so the sender stays quiet until the gear's target picker names one. A board that carries any drill filter ignores value filters, even when its drill filters are ambiguous.

Value

The block id, "" when the board offers no single candidate.

Examples

ctrl_auto_target(session = shiny::MockShinySession$new())

Cross-block external control

Description

Helpers that let one block set the externally controllable arguments (see the external_ctrl argument to blockr.core::new_block()) of another block on the same board, through the board's regular update channel. A drill-down chart can feed a function block whose function calls ctrl_send() to push the clicked patient into a patient-profile block. Sender and target share no data link.

Usage

ctrl_send(target, ..., session = shiny::getDefaultReactiveDomain())

ctrl_clear(target, ..., session = shiny::getDefaultReactiveDomain())

install_ctrl_send(
  update,
  board = NULL,
  session = shiny::getDefaultReactiveDomain()
)

Arguments

target

Character(1). Block id of the target block on the board.

...

Named values to set, one per externally controllable argument of the target block, e.g. subject = "01-701-1015".

session

Shiny session (defaults to the current reactive domain).

update

The board update reactive, as handed to board callbacks, plugins and dock extension servers.

board

The board reactive values, as handed to the same components (board$board is the current board). Optional: without it the channel still sends, but ctrl_targets() finds no candidates.

Details

install_ctrl_send() wires the channel up. Call it once per session from any board component that holds the board's update reactive: a board callback, a plugin or a dock extension server. It stores a send closure in session$userData, where ctrl_send() finds it.

Updates go through the board's full validation. Arguments that are not externally controllable on the target are rejected with a notification (see blockr.core:::validate_board_update).

Value

ctrl_send() returns TRUE (invisibly) when the payload was handed to the update channel, FALSE when no channel is installed (a warning is emitted once per session). ctrl_clear() returns TRUE (invisibly) when the caller owned the target's last claim and the reset was sent, FALSE otherwise. install_ctrl_send() returns the send closure, invisibly.

Semantics under lazy evaluation

ctrl_send() writes state and never reads another block's result, so it adds nothing to any evaluation closure. A function block calling it sends only while it is on screen. Repeated sends of an unchanged value are no-ops (apply_block_mod_delta() compares with identical()).

Clearing (ctrl_clear())

The undo side of ctrl_send(). It resets the target's controllable arguments only if the last ctrl_send() to that target came from the same block. A sender that re-evaluates without a drill (at startup, on a board restore, or while a different sender's claim is active on the target) owns nothing and does nothing. The values passed via ... define "cleared" for the target, e.g. state = list(columns = list()) empties a value filter.

Examples

# Inside a function block fn (always qualify: fns are deparsed):
# function(data) {
#   ids <- unique(data$USUBJID)
#   if (length(ids) == 1L) {
#     blockr.viz::ctrl_send("profile", subject = ids)
#   }
#   data
# }

Controllable blocks on the board

Description

The block ids a sender may point at: every block on the board of the given class. It populates the target picker of the drill senders and is available to a hand-rolled sender that wants one too.

Usage

ctrl_targets(
  class = "value_filter_block",
  session = shiny::getDefaultReactiveDomain()
)

Arguments

class

Character(1). Block class to look for. The default is the value filter block, the target shape the senders in this package push (a state of filter conditions).

session

Shiny session (defaults to the current reactive domain).

Details

Returns character() when no channel is installed, or when install_ctrl_send() was called without board.

Value

A named character vector of block ids, named by block name (falling back to the id). Empty when there is no channel or no candidate.

Examples

# Outside a board with the control channel there is nothing to target
ctrl_targets(session = shiny::MockShinySession$new())

Resolve a drilled summary row back to the source rows behind it

Description

A drill on a structured (annotated) table yields a subset of the display frame: the clicked row, not the records it summarises. The row carries the machine claim (.variable / .variable_level, plus any enclosing ⁠.group<k>⁠ pairs), so the records are recoverable from the frame the table was computed from. drill_source() returns the source rows that match a drilled annotated frame.

Usage

drill_source(x, source = NULL, columns = NULL, unclaimed = c("none", "all"))

Arguments

x

A drilled annotated data frame, or an object coercible via as_annotated_df().

source

Data frame to resolve against. Default NULL = the input's source_data attribute.

columns

Real source columns the claim is read from, for an aggregated table. Default NULL = read the ARD identity columns (.variable / .variable_level, ⁠.group<k>⁠ pairs) instead.

unclaimed

What a frame that claims nothing resolves to: "none" (default), a zero-row frame, or "all", the whole source.

Details

The frame comes from attr(x, "source_data"), which a producer stamps when it summarises. Pass source to resolve against another frame.

The claim rule is the one of the control channel (ctrl_send()): a dimension becomes a condition only when the drilled subset resolves it to exactly one value. An undrilled table claims nothing and unclaimed decides what comes back. A structured table carries ARD identity columns and columns stays NULL. An aggregated table (one display row standing for many records) has none: name its group columns in columns. A frame with neither errors instead of reporting zero rows.

Value

A subset of source: the rows the claim selects. When nothing is claimed, a zero-row frame or the whole source (unclaimed).

Rows defined by a predicate

A display row such as "Any Serious AEs" is not a level of anything. A producer writes the predicate it counted with on a .filter column, as an R expression string that yields a logical vector when evaluated against source. It composes with the pairs: a predicate row inside a treatment column resolves to the rows matching the predicate and in that arm. A frame carrying .filter needs no .variable / .variable_level.

See Also

as_annotated_df(), new_table_block() (drill = "source")

Examples

tbl <- summary_table(iris, vars = "Species")
# The rows behind the second row of the table, a click on "versicolor"
nrow(drill_source(tbl[2, ], source = iris))

Cell-colour spec for a table

Description

How numeric cells are painted; the data is never changed. "diverging" is a scale centred on 0 (a correlation matrix), "sequential" a low to high ramp, "bar" an in-cell bar scaled per column on absolute values.

Usage

drilldown_table_color(
  type = c("diverging", "sequential", "bar"),
  domain = NULL,
  palette = NULL,
  columns = NULL,
  source = NULL
)

Arguments

type

"diverging", "sequential", or "bar".

domain

NULL to infer from the data (symmetric around 0 for diverging), or c(min, max). Ignored for "bar".

palette

NULL for the defaults, or colours: three for diverging (low, mid, high), two for sequential, one for the bar.

columns

NULL for every numeric column, re-resolved on new data, or the columns to paint. A missing column is skipped.

source

NULL to paint by the cell's own value, a column name to paint every shaded column by that column, or a template such as "{col} (sev)" for one companion per column. Source columns are hidden and must be numeric. Diverging and sequential only.

Value

A cell-colour spec list.

Examples

drilldown_table_color("sequential", domain = c(0, 100))

Read an exhibit

Description

The only way an exporter reads an exhibit.

Usage

exhibit_data(x, display = FALSE)

exhibit_picture(x)

exhibit_render(x)

exhibit_titles(x)

exhibit_kind(x)

exhibit_meta(x)

Arguments

x

A viz_exhibit.

display

For exhibit_data(): TRUE rounds the numbers to the exhibit's digits as text, the way the screen shows them (for a web page or a slide); FALSE keeps the values (for a spreadsheet, which rounds with a number format instead).

Value

exhibit_data() a data frame; exhibit_picture() a chart_capture or NULL; exhibit_render() the render object or NULL; exhibit_titles() a list of title, subtitle and caption; exhibit_kind() "table" or "chart"; exhibit_meta() the named list.

Examples

ex <- new_viz_exhibit(summary_table(iris, vars = "Species"),
                      title = "Species", kind = "table")
exhibit_data(ex)
exhibit_titles(ex)
exhibit_kind(ex)
exhibit_meta(ex)
exhibit_picture(ex)
exhibit_render(ex)

Options That Tune an Exported Table

Description

Everything the table exporters read from options(). An app sets them once at startup; none is required. The values below are the defaults. A board option for the same thing wins.

Fitting a table to a slide

The exporter shrinks a table before it breaks it, and carries it downward before it deals its columns sideways.

blockr.viz.ft_min_font_size (11)

How small the type may go before a table is split. One floor, both axes. The board option exhibit_min_font_size ("Smallest table font", new_exhibit_font_option()) overrides it, and 5pt is a hard floor under both.

blockr.viz.ft_font_size (13)

The size a table starts at, before any shrinking.

blockr.viz.ft_footer_gap (0.05)

Inches left above whatever the layout puts at the foot of the slide (footer, date, slide number). 0 lets a page run right up to it.

blockr.viz.ft_header_break_tol (0, off)

Set to a fraction (say 0.6) to deal the columns over two sets of slides when a header word is cut past that much of itself. Off, the columns come apart only when a data cell no longer fits its own longest word.

blockr.viz.ft_fit_width (unset)

Total table width in inches. A deck sets it from the reference template; unset means natural widths, which suits html and pdf.

How the width is shared out

blockr.viz.ft_stub_share (0.3)

The most the row stub claims while the data columns are still short of their full headers. Raise it to keep long row labels on one line, lower it to feed the columns.

blockr.viz.ft_width_slack (1.04)

Margin for the measuring font differing from the rendering font. Raise it if a deck wraps where the export predicted it would not.

blockr.viz.ft_col_widths ("measured")

"even" is the positional rule: the stub takes a fixed width, the data columns share what is left equally, whatever their text needs.

Typography and appearance

blockr.viz.ft_font ("Inter")

The table's typeface. A deck sets it from the reference template's font scheme; an app naming a face wins.

blockr.viz.ft_header_bg (unset)

Header band colors. blockr.viz ships no palette of its own.

blockr.viz.ft_emphasis_colors (unset)

The ramp for emphasised columns.

blockr.viz.pptx_template (unset)

Reference deck for a block's own PowerPoint download, when the app has not set blockr.outline.template.

blockr.viz.paint_res (300)

Dots per inch for a summarize table, which reaches a slide as a picture because a PowerPoint cell cannot hold a glyph.

blockr.viz.gg_slide_fill (1)

How far a chart grows into the slide it is placed on.

Not options

static_table(cell_padding = ) (NULL, the flextable default of 5pt, tightened to 2 when a table cannot fit any other way) is a function argument. The stub's minimum width is a 1.2in constant in the width allocator.

See Also

static_table(), write_exhibit_pptx(), new_exhibit_font_option()

Examples

# A house style, set once at app startup.
old <- options(
  blockr.viz.ft_font_size = 12,
  blockr.viz.ft_min_font_size = 9,
  blockr.viz.ft_stub_share = 0.35
)
options(old)

Static HTML Renderer for a Display Table

Description

The HTML counterpart of static_table(): the same annotated data frame, rendered as the HTML display table the app draws, with its styles and its collapse script inlined. Nothing in the output talks to Shiny.

Usage

html_exhibit(
  x,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  max_height = NULL,
  default_expanded = NULL,
  ...
)

## Default S3 method:
html_exhibit(
  x,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  max_height = NULL,
  default_expanded = NULL,
  sortable = TRUE,
  collapsible = TRUE,
  ...
)

Arguments

x

A data frame or as_annotated_df()-coercible table object.

title, subtitle, caption

Table title / subtitle / footnote. NULL (default) takes them from the annotated data frame's display attributes, "" switches them off, as in static_table(). The default renderer ignores subtitle.

max_height

CSS max-height of the scroll container, or NULL (default) for none.

default_expanded

Logical, or NULL (default) to decide from the table's height: a table that fits opens expanded, a taller one opens at its section rows. The threshold is getOption("blockr.viz.html_exhibit_expanded_max_rows") (24).

...

Passed to the method.

sortable, collapsible

Logical. Whether the default method's table keeps its click-to-sort headers and its fold chevrons.

Details

Called by static_exhibit() when the render target is HTML. It is a generic: an exhibit that carries its own renderer (the summarize table) answers for itself, and everything else is drawn as the display table.

Value

A htmltools::tagList().

See Also

static_exhibit(), static_table()

Examples

tbl <- summary_table(iris, vars = "Sepal.Length", by = "Species")
html_exhibit(tbl, title = "Sepal length by species")

Interactive table

Description

Draws a table the way new_table_block() draws it on screen, for use in another block's UI. x is anything as_annotated_df() accepts: a plain data frame, an annotated data frame (shown with its sections and spanner headers), or a table object such as a composer table. static_table() is the print counterpart.

Usage

interactive_table(
  x = NULL,
  drill = TRUE,
  drill_target = NULL,
  sortable = TRUE,
  collapsible = TRUE,
  search = TRUE,
  max_height = "600px",
  elem_id = NULL
)

update_interactive_table(
  session,
  elem_id,
  x,
  drill = TRUE,
  drill_target = NULL,
  sortable = TRUE,
  collapsible = TRUE
)

Arguments

x

A data frame, an object with an as_annotated_df() method, or NULL for an empty table. update_interactive_table() also takes a string or an htmltools tag, whose text is shown instead of a table.

drill

TRUE makes rows clickable: an annotated table claims the clicked row, a plain one its first column. A column name picks the column of a plain table. FALSE turns clicks off.

drill_target

Id of the block a click is sent to, or NULL. With a target, a click is an event (a flash and a send) rather than a selection that stays highlighted.

sortable

Can column headers sort the rows?

collapsible

Can section headers collapse?

search

Draw a search box above the table?

max_height

CSS height limit of the scroll box, or NULL to let the table grow with the page.

elem_id

The table's namespaced id. Required for a drill and for update_interactive_table().

session

The Shiny session (a module session works).

Details

The table searches, sorts and collapses in the browser. A row click is sent to the server as input[[paste0(elem_id, "_select")]], the selection the table block holds, so the calling block handles the drill.

update_interactive_table() replaces the table inside a drawn interactive_table(), so the search text and the scroll position stay. Draw it with x = NULL and fill it from the server.

Value

interactive_table(): an htmltools::tagList(). update_interactive_table(): called for its side effect.

See Also

static_table(), new_table_block()

Examples

interactive_table(head(mtcars))

# An annotated table whose rows send a click as input$tbl_select
interactive_table(summary_table(iris, vars = "Species"), drill = TRUE,
                  elem_id = "tbl")
interactive_table(head(mtcars), drill = FALSE)

Chart block

Description

A block that draws its input as an interactive chart (ECharts) and, when asked to, filters the blocks downstream by the marks a reader clicks. Its output is its input, filtered by the last click.

Usage

new_chart_block(
  type = "bar",
  ...,
  category = NULL,
  value = NULL,
  func = "count",
  x = NULL,
  xend = NULL,
  open = NULL,
  y = NULL,
  color = NULL,
  facet = NULL,
  facet_row = NULL,
  series = NULL,
  label = NULL,
  orientation = NULL,
  position = "stack",
  sort_by = NULL,
  sort_dir = NULL,
  value_labels = FALSE,
  format = "number",
  unit = "",
  y_transform = "identity",
  x_transform = "identity",
  x_limits = NULL,
  y_limits = NULL,
  x_ticks = NULL,
  y_ticks = NULL,
  tooltip = NULL,
  drill = NULL,
  line_width = 1,
  point_size = 1,
  connect = "straight",
  value_lines = NULL,
  x_lines = NULL,
  ymin = NULL,
  ymax = NULL,
  linetype = NULL,
  shape = NULL,
  x_ranges = NULL,
  legend = "bottom",
  highlight = NULL,
  smoother = "none",
  identity_line = FALSE,
  box_points = "none",
  summary = NULL,
  whiskers = NULL,
  connect_centers = FALSE,
  band_window = "adaptive",
  band_size = 45,
  band_min_n = 12L,
  id = NULL,
  ref_min = NULL,
  ref_max = NULL,
  ref_lines = NULL,
  ref_line_colors = NULL,
  waterfall_totals = NULL,
  bins = 30L,
  show_n = "none",
  missing = "level",
  percent_of = "facet",
  facet_scales = "fixed",
  facet_cols = getOption("blockr.viz.facet_cols"),
  download = TRUE,
  title = NULL,
  subtitle = NULL,
  caption = getOption("blockr.viz.default_caption"),
  drill_target = "",
  drill_table = "",
  script = NULL,
  script_values = list(),
  selection = NULL
)

Arguments

type

Chart type. Aggregated: bar, waterfall, pie, treemap, boxplot, pointrange. One mark per row: scatter, line, area, band. Also histogram and gantt (intervals on lanes). One of "bar", "histogram", "waterfall", "pie", "treemap", "boxplot", "pointrange", "scatter", "line", "area", "band", "gantt". Default: "bar".

...

Arguments for blockr.core::new_block() (block_name, ...), and argument names of blockr.viz before 0.3.0, which are translated with a warning.

category

Column whose values become the bars, slices, tiles, boxes or points: one mark per value. The same whichever way a bar lies. Default NULL: unset.

value

Column func aggregates per category; unused by func = "count". Boxplot and pointrange: the column whose spread each box or point range shows. Default NULL: unset.

func

Aggregation of value per category. "identity" draws the value as is; "pct_distinct" is the share of the panel's distinct values (see percent_of). One of "count", "count_distinct", "pct_distinct", "mean", "median", "sum", "min", "max", "identity". Default: "count".

x

Column on the horizontal axis of a scatter, line, area or band. Histogram: the column that is binned. Gantt: the interval start. Default NULL: unset.

xend

Interval end. A row without an end is drawn as a dot at x. Default NULL: dots at x.

open

Logical column. TRUE draws an arrowhead after the bar's end (still ongoing); a TRUE row without an end runs to the last x drawn. Default NULL: no arrow.

y

Column on the vertical axis. Gantt: the lane. Default NULL: unset.

color

Column mapped to color, at most 15 levels. Default NULL: no color.

facet

Column to facet by, one small panel per level. Default NULL: one panel.

facet_row

Column whose levels make the rows of a panel grid, facet making its columns. Each row gets its own y scale when facet_scales is "free_y" or "free". Default NULL: panels wrap.

series

Column whose values split rows into separate series: one line or point group per value, the bar label on a gantt. Default NULL: no series.

label

Column written on the marks. A bar, slice or tile shows it only when its rows agree on one value. Default NULL: no labels.

orientation

Which way a bar, boxplot or pointrange lies. It changes no mapping: category stays the category either way. One of "horizontal", "vertical". Default NULL: horizontal for bar, vertical for boxplot and pointrange.

position

Layout of a color split: stacked, side by side, or to 100%. One of "stack", "dodge", "fill". Default: "stack".

sort_by

Category order: "value", "data", "alpha", or a column (its per-category minimum). Gantt: "onset", "alpha" or a column. NULL: "data" for date, numeric and factor categories, else "value". Default NULL: by type.

sort_dir

Sort direction. One of "asc", "desc". Default NULL: desc for sort_by = "value", else asc.

value_labels

TRUE writes each bar's value at its end: a stack its total, a filled bar each share. Default: FALSE.

format

How numbers print: "number" (separators and up to two decimals, trailing zeros dropped; a value that would round to 0 keeps two significant digits), "compact" (1.2K, 3.4M), "percent" (a fraction times 100, with "%"), or a whole number of decimals from 0 to 6, printed exactly. Default: "number".

unit

Free text printed after the number ("CHF"); headers carry it once. Default: "".

y_transform

"log10" draws a base-10 y axis. Values at or below zero are not drawn; a note under the chart counts them. One of "identity", "log10". Default: "identity".

x_transform

As y_transform, for the x axis of a scatter. One of "identity", "log10". Default: "identity".

x_limits

The x axis from and to, as c(0, 100); NA at either end is auto. Dates as "2024-01-01". Marks outside are cut off, not dropped from the data. Drag zoom works inside the limits, and a reset returns to them. A subtitle template names them as ⁠{@x_limits}⁠, printed as "2024-01-01 to auto". Default NULL: auto.

y_limits

As x_limits, for the value axis: y on a scatter, line, area or band, value's axis on the aggregated types, whichever way they lie. Default NULL: auto.

x_ticks

Where the x axis puts its ticks. One number is a step: 10 ticks every 10, at its multiples. On a date axis the step takes a unit, "7 days", "2 weeks", "month", "quarter" or "year"; days and weeks count from the axis start. Two values or more are the ticks themselves, c(0, 25, 50, 100), dates as "2024-01-01". A log axis takes a list only. A list keeps the axis range; a step rounds an auto end out to the next tick. A subtitle template names it as ⁠{@x_ticks}⁠, printed "every 7 days" or "at 0, 25, 50, 100". Default NULL: auto.

y_ticks

As x_ticks, for the value axis: y on a scatter, line, area or band, value's axis on the aggregated types, whichever way they lie. Default NULL: auto.

tooltip

Extra columns shown in each mark's tooltip. Default NULL: no extra columns.

drill

Column a click filters downstream on, or "auto" for the type's natural target (the clicked group, bin or lane). Default NULL: a click does nothing.

line_width

Line width relative to the default (1). Default: 1.

point_size

Marker size relative to the default (1). Default: 1.

connect

How a line connects its points. One of "straight", "monotone", "step_start", "step_middle", "step_end". Default: "straight".

value_lines

Positions of dashed reference lines across the value axis: value's axis, y on a scatter, line, area or histogram. Names are labels. Text form: "Target: 4; 6". Default NULL: no lines.

x_lines

Positions of dashed reference lines across x, or across a bar's category axis: numbers, dates or category values. Names are labels. Default NULL: no lines.

ymin

Columns holding the lower end of an interval per row, the first the outermost. A line draws shaded bands, a scatter error bars. Default NULL: no interval.

ymax

Columns holding the upper end of an interval, as ymin. Default NULL: no interval.

linetype

Column whose values set a line's dash: the first value is solid, the others dashed. Default NULL: all solid.

shape

Column whose values set each point's marker: circle, triangle, diamond, square, rounded square, pin, arrow, then again. Levels in factor order, else sorted; a missing value is a circle. A line chart shows its points when it is set. Default NULL: all circles.

x_ranges

Named stretches of x shaded behind the marks, as list(Recession = c("2008-01-01", "2009-06-30")). Text form: "Recession: 2008-01-01 to 2009-06-30; ...". Default NULL: no ranges.

legend

Where the color legend goes. "marks" writes the names on the marks where the type has room, and keeps the legend elsewhere. One of "bottom", "top", "marks", "none". Default: "bottom".

highlight

One column and some of its values, as list(country = "Switzerland"). Matching marks keep their color; every other mark is gray. Default NULL: no highlight.

smoother

Trend line, fit per color or series group and per panel. One of "none", "lm", "loess". Default: "none".

identity_line

TRUE draws a dashed y = x line. Default: FALSE.

box_points

"outliers" draws the points beyond the whiskers. One of "none", "outliers". Default: "none".

summary

Statistic of a boxplot's body, a pointrange's interval or a band's inner range. One of "median_q1_q3", "mean_sd", "mean_2sd", "mean_se", "mean_ci95", "p5_p95", "p10_p90", "min_max". Default NULL: median_q1_q3 on a boxplot, mean_se on a pointrange.

whiskers

Outer interval: Tukey fences or any summary statistic. One of "tukey", "median_q1_q3", "mean_sd", "mean_2sd", "mean_se", "mean_ci95", "p5_p95", "p10_p90", "min_max". Default NULL: tukey on a boxplot, p10_p90 on a band.

connect_centers

TRUE joins a pointrange's centers in category order. Default: FALSE.

band_window

"adaptive" grows the window at each point until it holds band_size individuals; "fixed" uses band_size as a half-width in x units. One of "adaptive", "fixed". Default: "adaptive".

band_size

Individuals per window, or the half-width; see band_window. Default: 45.

band_min_n

Points with fewer individuals than this are not drawn. Default: 12L.

id

Column that identifies an individual, counted distinct by the band and by show_n. Default NULL: count rows.

ref_min

Column holding a lower reference limit per row, drawn as a dashed line at its median and labelled with its spread. Default NULL: no lower limit.

ref_max

Column holding an upper reference limit per row, as ref_min. Default NULL: no upper limit.

ref_lines

Columns holding reference limits (a normal range, grade thresholds). Per panel, each column with a value in the panel's rows draws a dashed horizontal line at the mean of those values, labelled with the column's label, else its name. Default NULL: no lines.

ref_line_colors

Colors of the ref_lines, by column, as list(LLN = "#4DAF4A", ULN = "#4DAF4A"). A column without one takes the reference line color. Default NULL: the reference line color.

waterfall_totals

Steps of a waterfall drawn as totals, from zero. Default NULL: no totals.

bins

About how many bins x is cut into, at readable breaks. Default: 30L.

show_n

Observation counts in labels, e.g. "Female (12)". One of "none", "axis", "facet", "both". Default: "none".

missing

Rows whose category is missing: "level" gives them their own ("(Missing)"; a click on it gives the rows with no value), "drop" removes them from the categories. One of "level", "drop". Default: "level".

percent_of

The role whose levels a pct_distinct denominator is taken within, or "total" for the whole chart. One of "facet", "category", "color", "total". Default: "facet".

facet_scales

"fixed" shares one scale across panels, "free" lets each panel size itself, "free_y" frees y only (scatter, line and band). In a grid (facet_row) "free_y" shares the value axis within a row (x on horizontal bars and a gantt) and the categories across all panels; "free" also shares the other axis within a column. One of "fixed", "free", "free_y". Default: "fixed".

facet_cols

Panels per row. NULL fits as many as the card is wide. Default: the option blockr.viz.facet_cols, else NULL.

download

TRUE offers the block for download. Default: TRUE.

title

Text above the block. NULL uses the input's label, "" shows nothing, any other string is a template resolved against the data: {col}, {label(col)}, {n}, {n_distinct(col)}, {filters}, ⁠{@arg}⁠ (one of the block's settings, clickable), and ⁠[...]⁠ for a clause that disappears when its setting is empty. Default NULL: the input's label.

subtitle

Text under the title, a template as title. Default NULL: the input's subtitle.

caption

Text below the block, a template as title. Defaults to the option blockr.viz.default_caption. Default: the option blockr.viz.default_caption, else NULL.

drill_target

Beta. The id of a filter block a click is sent to, or "auto" for the board's drill destination. With a target set a click is an event and the block holds no selection. Default: "".

drill_table

Beta. The table in the target's dm the click applies to. Default: "".

script

Experimental. R code run on the input before the block sees it. Its top-level plain-value assignments become controls on the block. A line annotated ⁠#| setting⁠ (by <- "AEDECOD" #| setting) is no control: it takes the block's own setting of that name, or the first summary's field (facet). Default NULL: no script.

script_values

Settings of the script's controls, by variable name. The script code, not the spec, makes each one a title slot. Default: list().

selection

What a click or brush selected. Written by the block, saved so a restored board keeps it; leave it NULL. Default NULL: nothing selected.

Details

Every argument that names a column names a data column, never a literal value. Each does one thing: color colors, series splits into series, facet splits into panels, label writes on the marks.

Value

A chart block (class chart_block), for a blockr board.

Mapping

The aggregated types (bar, waterfall, pie, treemap, boxplot, pointrange) draw one mark per value of category. A bar, waterfall, pie or treemap aggregates value with func; func = "count" counts rows and needs no value. A boxplot or pointrange shows the spread of value. orientation only turns the marks: bars lie horizontal and boxes stand vertical unless it says otherwise, and category stays the category either way.

x and y are the screen axes of the types that draw one mark per row (scatter, line, area, band). A histogram bins x; a gantt draws x to xend on one lane per value of y. An aggregated type mapped with x or y and no category is an error.

ymin and ymax name intervals in pairs, the first pair the outermost: bands on a line or an area, error bars on a scatter. They must name the same number of columns, or the block is an error.

Clicks

A click filters only when drill is set: to a column, or to "auto", the clicked mark's own category, bin or lane. The block's output is then the rows behind the clicked mark until the reader clicks another mark or Clear. A brush on a scatter or a line filters to the points inside the rectangle. With drill_target set, a click, a point or a brush is sent to that filter block instead, once (a brush when the drag ends), and the chart keeps no selection of its own. A second click on the same mark clears the target. The data view shows the last drill until then.

Titles

title, subtitle and caption are templates. NULL takes the input's own label, subtitle or caption, and "" shows nothing. In a template, {col} lists a column's values (up to eight), {label(col)} its label, {n} the number of rows, {n_distinct(col)} the number of distinct values, {filters} the filters upstream, {highlight} what highlight picks, and ⁠{@arg}⁠ the value of one of the block's arguments, which the reader can change by clicking it. Text in ⁠[...]⁠ disappears when a value in it is empty.

Older code and boards

Argument names and values of blockr.viz before 0.3.0 (chart_type, group, bar_mode, y_scale, ...) still work in code, with a warning, and boards saved with them restore unchanged. A value an argument does not take is an error. Any other name is kept as a block attribute, for blockr.core and other packages (blockr.dock's visible).

See Also

new_table_block()

Examples

# Aggregated: mean sepal length per species, as horizontal bars
new_chart_block(type = "bar", category = "Species", value = "Sepal.Length",
                func = "mean")

# The same standing up
new_chart_block(type = "bar", category = "Species", value = "Sepal.Length",
                func = "mean", orientation = "vertical")

# One mark per row: a scatter colored by species, filtering on click
new_chart_block(type = "scatter", x = "Sepal.Length", y = "Petal.Length",
                color = "Species", drill = "auto")

# A line over time
new_chart_block(type = "line", x = "date", y = "unemploy")

# Distribution: a box per category
new_chart_block(type = "boxplot", category = "cyl", value = "mpg")

# Histogram: one numeric column, cut into bins
new_chart_block(type = "histogram", x = "mpg", bins = 10)

# Timeline: intervals on lanes
new_chart_block(type = "gantt", x = "start", xend = "end", y = "task")

if (interactive()) {
  blockr.core::serve(
    new_chart_block(type = "bar", category = "Species",
                    value = "Sepal.Length", func = "mean", drill = "auto"),
    data = list(data = iris)
  )
}

Control-channel bridge extension

Description

A dock extension with no UI that installs the cross-block control channel (install_ctrl_send()) on the board, so that blocks can call ctrl_send() / ctrl_clear() and senders can offer a target picker (ctrl_targets()).

Usage

new_ctrl_bridge_extension(...)

Arguments

...

Forwarded to blockr.dock::new_dock_extension(). On restore, dock calls this constructor with the ctor/pkg it recorded, so the dots must be here for a saved board to come back.

Details

A block server cannot open the channel itself because it never sees the board's update reactive. A dock extension does, and a board carries it.

Value

A dock_extension (see blockr.dock::new_dock_extension()).

Wiring

Add it to the board's extensions and to no grid, since it renders an empty div:

new_dock_board(
  extensions = list(
    dag = blockr.dag::new_dag_extension(),
    ctrl_bridge = blockr.viz::new_ctrl_bridge_extension()
  ),
  grids = list(Main = dock_grid(ext("dag")))
)

A board needs exactly one bridge. The registry that lets ctrl_clear() clear only its own claim lives inside the closure install_ctrl_send() builds, so two bridges give two senders separate views of who owns what.

Saved boards

Dock rebuilds an extension from its constructor name and package, so the bridge is an exported constructor. A board saved by an app without the bridge comes back without a channel and needs one re-save.

Examples

if (interactive()) {
  new_ctrl_bridge_extension()
}

Smallest exhibit font board option

Description

Board option that adds "Smallest table font" to the board sidebar: the size an exported table shrinks to before it is split over several slides.

Usage

new_exhibit_font_option(value = 11, category = "Table options", ...)

Arguments

value

Default floor in points.

category

Settings sidebar category.

...

Forwarded to blockr.core::new_board_option().

Details

The paginator shrinks a table to this size on both axes before it carries rows onto another slide or deals columns over several. Set it to the base size (13pt) to forbid shrinking. When even the smallest allowed size does not fit, the table is split and the download says so. One value serves the decks built by blockr.outline and the PowerPoint download of every block.

Value

A board_option object.

See Also

write_exhibit_pptx(), pptx_add_exhibit()

Examples

new_exhibit_font_option()

Picker block (deprecated)

Description

Deprecated: bind chart and table mappings to the source columns directly and put a group switch in the board's filter. The block stays so that boards saved with it restore with the block and its links.

Usage

new_picker_block(state = list(pickers = list()), ...)

Arguments

state

List with pickers – a list of picker entries, each list(into, choices, selected, multiple, optional). Empty (default) seeds one empty, inert picker (into = "value") on first data arrival for the builder to fill.

...

Forwarded to blockr.core::new_transform_block()

Details

A curated column picker for locked, dashboard-style boards (the value-selection sibling of blockr.dm's value filter block): the builder defines one or more pickers in the gear, the viewer operates one select per picker and nothing else. Each picker fixes which columns are offered (choices), which is picked (selected), and – crucially – the name of the output column the pick lands in (into). Downstream blocks map to the into names, which never change, so switching the pick never requires reconfiguration.

Semantics per picker:

  • single (default): the picked column is copied into into, with its label attribute carried along (a chart's axis title follows the pick) and a blockr_source attribute naming the source column – a drill on the copy claims the original column, so a cross-block send still hits a value filter sitting on the source table. Copies, not renames, so two pickers may pick the same source column (e.g. a measure against itself).

  • multiple = TRUE (at most one picker): the picked columns pivot long – values into into, the measure identity into ⁠<into>_measure⁠ (a factor of column labels, ready for facetting). Offered-but-unpicked columns of this picker are dropped so the schema never depends on the pick.

  • optional = TRUE (single pickers only): the face gains a leading (none) entry. Selecting it leaves the picker inert – no output column – so a downstream chart mapped to into drops that aesthetic (no legend / no facet strip) rather than showing a single phantom group. Use it for optional roles like colour or facet; leave it off for required roles (x/y axes).

UI follows the blockr design system: Blockr.Select controls on the block face (one per picker, labelled by into), and the picker definitions in the gear-toggled settings band, like the value filter's filter list. Each gear row carries move-up / move-down buttons next to its remove button: the order of the pickers is the order of the controls on the face, so that is how the builder arranges them. Every column qualifies as a candidate – a picker can just as well drive a grouping or color dimension as a measure. A picker's offer list starts empty: the builder curates which columns the viewer sees. An empty offer list is inert (no output column) until it has choices, which also covers clearing it mid-edit to refill.

The state is externally controllable (external_ctrl): a board modification carrying list(pickers = ...) sets the pick from outside – another block, the assistant, or the block card's control panel – and the face follows. Such a payload PATCHES the authored definition: entries match by into, only the fields they carry override, and pickers the payload does not mention keep their state. So steering one picker is list(pickers = list(list(into = "value", selected = "AEBODSYS"))), with the curated offer list, the flags and the sibling pickers left alone. An entry whose into matches no picker adds one, but only when it also brings choices – otherwise it is a typo'd into, not a request for a control that offers nothing. A payload that is not shaped like a picker list at all is ignored, and the block keeps its last good definition.

Design records: blockr.docs design-system/target select-controls.html (control style) and measure-switch-proposals.html (schema; the picker generalizes the measure switch to n pickers with editable output names).

Value

A transform block of class picker_block

Examples

if (interactive()) {
  library(blockr.core)
  serve(
    new_picker_block(
      state = list(pickers = list(
        list(into = "value", choices = c("Sepal.Length", "Sepal.Width"),
             selected = "Sepal.Length", multiple = FALSE)
      ))
    ),
    data = list(data = iris)
  )
}

Summarize table block (deprecated)

Description

Deprecated: use new_table_block() with layout = "groups", which takes the same summaries. This constructor translates its arguments and returns a table block, with a deprecation warning. Boards saved with it restore as table blocks, show a toast that asks the user to save the board, and save as table blocks from then on.

Usage

new_summarize_table_block(...)

Arguments

...

Arguments of the former summarize table block (by, summaries, id_var, group, value, func, ...), translated to new_table_block()'s. missing defaults to "drop": the old block drew no row for a missing group.

Value

A blockr transform block of class table_block.

Examples

new_summarize_table_block(
  by = "Species",
  summaries = list(list(type = "simple", func = "count", show = "bar"))
)

Summary table block (deprecated)

Description

Deprecated: use new_table_block() with layout = "variables", which draws the same table and takes the same settings. This constructor translates its arguments (vars, by, stats, add_overall, ...) and returns a table block, with a deprecation warning. Boards saved with it restore as table blocks, show a toast that asks the user to save the board, and save as table blocks from then on.

Usage

new_summary_table_block(...)

Arguments

...

Arguments of the former summary table block, translated to new_table_block()'s.

Value

A blockr transform block of class table_block.

Examples

new_summary_table_block(vars = c("AGE", "SEX"), by = "ARM")

Table block

Description

A block that shows its input as an interactive table and, when asked to, filters the blocks downstream by the row a reader clicks. Its output is its input, filtered by the last click.

Usage

new_table_block(
  layout = "records",
  ...,
  by = character(),
  rowname = NULL,
  columns = NULL,
  summaries = list(),
  id = NULL,
  percent_of = "facet",
  missing = "level",
  color = "auto",
  shadings = list(),
  format = "number",
  unit = "",
  look = "table",
  facet_layout = "by_summary",
  group_rows = "name",
  open = "none",
  row_sections = NULL,
  row_groups = NULL,
  sort_by = "value",
  sort_dir = NULL,
  top_n = NULL,
  value_labels = TRUE,
  column_axis = TRUE,
  bar_width = "fit",
  drill = NULL,
  search = TRUE,
  sortable = TRUE,
  collapsible = TRUE,
  download = TRUE,
  stats = "mean_sd",
  sections = character(),
  total = FALSE,
  total_label = "Total",
  nest = FALSE,
  title = NULL,
  subtitle = NULL,
  caption = getOption("blockr.viz.default_caption"),
  drill_target = "",
  drill_table = "",
  script = NULL,
  script_values = list(),
  selection = NULL
)

Arguments

layout

What a row is: "records" (the input rows), "groups" (one row per level of by, one column per summary) or "variables" (a Table 1: one row per statistic or level, one column per level of by). One of "records", "groups", "variables". Default: "records".

...

Arguments for blockr.core::new_block() (block_name, ...); gear, a table_gear() for a block built on the table, and class, classes put before table_block (neither is saved, the block's own constructor sets them); and argument names of blockr.viz before 0.3.0, which are translated with a warning.

by

Grouping columns, outer first, at most two. Records: rows under one collapsible header per level. Groups: one row per level. Variables: one column per level. Default: character(0).

rowname

The stub column: first column, row label. Default NULL: first column.

columns

Columns shown beside the row names, in order. Default NULL: all columns.

summaries

Groups: the table's columns. Variables: its variables. An ordered list of typed summaries, each list(type = , ...): simple, dist, field, sparkline, spans, pair, expr, custom. Keys per type: see the Summaries section of ?new_table_block. Default: list().

id

Column whose distinct values are counted instead of rows, so a count reads as "subjects with at least one event". Default NULL: count rows.

percent_of

The base of a count's percentage: the rows of the column's own facet level, or the table. One of "facet", "total". Default: "facet".

missing

Rows whose category is missing: "level" gives them their own ("(Missing)"; a click on it gives the rows with no value), "drop" removes them from the categories. One of "level", "drop". Default: "level".

color

Column whose colors tint the rows, from the board's scale map. "auto" uses the stub column when the scale map has it. Default: "auto".

shadings

Cell color rules, each list(mode, columns, domain) with mode one of "diverging", "sequential", "bar". A column belongs to the first rule that names it. Default: list().

format

How numbers print: "number" (separators and up to two decimals, trailing zeros dropped; a value that would round to 0 keeps two significant digits), "compact" (1.2K, 3.4M), "percent" (a fraction times 100, with "%"), or a whole number of decimals from 0 to 6, printed exactly. Default: "number".

unit

Free text printed after the number ("CHF"); headers carry it once. Default: "".

look

"compact" rotates the column titles and draws tile summaries as square cells (a heatmap). "cards" draws one card per summary (groups) or per column (records). One of "table", "compact", "cards". Default: "table".

facet_layout

Column order of faceted summaries. "by_level" needs exactly one facet column in the table. One of "by_summary", "by_level". Default: "by_summary".

group_rows

What the outer rows of a nested table (two by columns) show. "name": the group's name and its number of rows, across the row, with the groups open. "summary": every summary over the group's rows, on the group's line. A summary with func = "identity" stays empty on an outer row either way. One of "name", "summary". Default: "name".

open

With group_rows = "summary", whether the outer rows start closed ("none") or open ("all"). The header's button opens and closes them all either way. One of "none", "all". Default: "none".

row_sections

Column naming the section each inner row of a nested table belongs to. An outer row whose inner rows fall in more than one section shows each section's name, in small bold type, above its first row. One section: no title. Sorting by a column drops the titles. Default NULL: no titles.

row_groups

Column whose value groups the outer rows: each value heads its rows, which a click on it folds, in the column's level order (a factor) or alphabetical. An outer row takes the first value its records have; rows without one come last, under no heading. A column the data lacks: no grouping. Default NULL: no grouping.

sort_by

Row order: "value", "data", "alpha", a summary's name, a facet level, or a numeric column (its per-row minimum). Default: "value".

sort_dir

Sort direction. One of "asc", "desc". Default NULL: desc for sort_by = "value", else asc.

top_n

Rows past the cut fold into one "Other" row. Default NULL: all rows.

value_labels

TRUE writes each mark's number beside it. Default: TRUE.

column_axis

TRUE draws the domain strip under each glyph column. Default: TRUE.

bar_width

Mark length: fit the column, or 90, 150 or 240 px. One of "fit", "narrow", "medium", "wide". Default: "fit".

drill

Turns the row click on. Records: the column a click filters on, "auto", or "source" (the input's source rows). Groups and variables: "auto". Default NULL: off.

search

Show the search input. Default: TRUE.

sortable

Allow sorting by the column headers. Default: TRUE.

collapsible

Allow collapsing the group rows of a nested table. Default: TRUE.

download

TRUE offers the block for download. Default: TRUE.

stats

Rows shown for numeric variables, in the order given. One of "n", "n_pct", "mean", "sd", "mean_sd", "median", "median_q1_q3", "q1_q3", "min_max". Default: "mean_sd".

sections

Outer header rows above the variables. Default: character(0).

total

TRUE adds a column over all levels of by. Default: FALSE.

total_label

Header of the overall column. Default: "Total".

nest

TRUE nests adjacent categorical hierarchies. Default: FALSE.

title

Text above the block. NULL uses the input's label, "" shows nothing, any other string is a template resolved against the data: {col}, {label(col)}, {n}, {n_distinct(col)}, {filters}, ⁠{@arg}⁠ (one of the block's settings, clickable), and ⁠[...]⁠ for a clause that disappears when its setting is empty. Default NULL: the input's label.

subtitle

Text under the title, a template as title. Default NULL: the input's subtitle.

caption

Text below the block, a template as title. Defaults to the option blockr.viz.default_caption. Default: the option blockr.viz.default_caption, else NULL.

drill_target

Beta. The id of a filter block a click is sent to, or "auto" for the board's drill destination. With a target set a click is an event and the block holds no selection. Default: "".

drill_table

Beta. The table in the target's dm the click applies to. Default: "".

script

Experimental. R code run on the input before the block sees it. Its top-level plain-value assignments become controls on the block. A line annotated ⁠#| setting⁠ (by <- "AEDECOD" #| setting) is no control: it takes the block's own setting of that name, or the first summary's field (facet). Default NULL: no script.

script_values

Settings of the script's controls, by variable name. The script code, not the spec, makes each one a title slot. Default: list().

selection

What a click or brush selected. Written by the block, saved so a restored board keeps it; leave it NULL. Default NULL: nothing selected.

Value

A table block (class table_block), for a blockr board.

Layouts

layout decides what a row is:

  • "records": the input's rows, with search, sort and cell colors (shadings, color). With by, rows sit under one collapsible header per level. A finished table from R code (a structured or annotated data frame, see as_annotated_df()) is drawn as it comes.

  • "groups": one row per level of by (or one row without it), one column per entry of summaries: counts and statistics as numbers, bars, dots, boxes, point ranges, sparklines or spans.

  • "variables": a Table 1. One row per statistic or level of each variable in summaries, one column per level of by, with stats, sections and a total column.

look draws any layout as a "table", a "compact" matrix (rotated column titles, tiles as a heatmap) or "cards" (one card per summary in groups, per column in records).

Clicks

A click filters only when drill is set. In records it names the column a click filters on, or "auto"; in groups and variables "auto" filters on the clicked row's groups. With drill_target set, a click is sent to that filter block instead, and the table keeps no selection of its own.

Older code and boards

Argument names of blockr.viz before 0.3.0 (value, group, pct_of, axis, ...) still work in code, with a warning. Boards saved with the table, tile and summary blocks restore as table blocks. A value an argument does not take is an error. Any other name is kept as a block attribute, for blockr.core and other packages (blockr.dock's visible).

Summaries

Each entry of summaries is a list with a type and the keys of that type. Keys left out take their default.

type = "simple"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • show: The mark. "tile" is a square cell, offered with look = "compact". One of "bar", "number", "dot", "tile". Default: "bar".

  • func: Aggregation per row group. An unknown value is an error. One of "count", "count_distinct", "sum", "mean", "median", "min", "max", "identity". Default: "count".

  • col: The column aggregated. Required unless func is "count". Default NULL: only with func = "count".

  • position: Layout of a color split on a bar. One of "stack", "dodge", "fill". Default NULL: by the measure.

  • fill: Tile only. The cell is painted by the worst level of this column (factor order, numeric order, else sorted). Default NULL: value ramp.

  • color: Color split, at most 15 levels. Default NULL: no color split.

type = "dist"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • show: The mark, or the statistic as text. One of "pointrange", "box", "text". Default: "pointrange".

  • col: Numeric column summarized. Required.

  • summary: Center and inner range, as the chart's summary. With show = "text" it is the printed statistic. One of "median_q1_q3", "mean_sd", "mean_2sd", "mean_se", "mean_ci95", "p5_p95", "p10_p90", "min_max", "none". Default: "median_q1_q3".

  • whiskers: Outer range, as the chart's whiskers. One of "tukey", "median_q1_q3", "mean_sd", "mean_2sd", "mean_se", "mean_ci95", "p5_p95", "p10_p90", "min_max", "none". Default NULL: Tukey on a box, none on a dot range.

  • color: Color split, at most 15 levels. Default NULL: no color split.

type = "field"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • col: Distinct values joined: up to 3, then "+n more"; over 8, "n values". Required.

  • optional: TRUE: a column the data lacks leaves the summary out of the table, with no error (a column a picker offered that the data no longer has). Default: FALSE.

type = "sparkline"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • x: Numeric column the line runs along. Required.

  • col: Numeric column drawn. Required.

  • ymin: Lower end of a band behind the line. Both or neither. Default NULL: no band.

  • ymax: Upper end of the band. Default NULL: no band.

  • summary: Reference band behind the line. One of "none", "mean", "mean_sd", "median_q1_q3". Default: "none".

type = "spans"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • x: Interval start, numeric or date, as the chart's gantt. Required.

  • xend: Interval end. Required.

  • label: Headlines the tooltip and keys the same-event highlight. Default NULL: no label.

  • tooltip: Extra columns in the tooltip. Default NULL: no extra columns.

  • size: The swimlane's share of the table: regular, wide (about half) or widest (all the room the other columns leave). One of "md", "lg", "xl". Default: "md".

  • color: Color split, at most 15 levels. Default NULL: no color split.

  • ticks: Positions drawn as thin ticks across the lane (visits). Read from the rows where it is set, so tick rows can sit in the same frame. Default NULL: no ticks.

  • band_x: Start of a dark line through the middle of the lane (a phase such as a trial period). Both or neither. Default NULL: no band.

  • band_xend: End of the line. Default NULL: no band.

  • event_x: Positions of point events, which may lie past the last segment (a churn date after the contract ended). Default NULL: no events.

  • event_shape: Event kind. Its levels take, in order, a filled triangle, an open triangle, a cross, a square and a vertical bar; further levels repeat them. Names the event in the tooltip and the legend. Default NULL: one shape.

  • open: Logical, per record. A record with a start, no end and TRUE is ongoing: it runs to the axis end with an arrowhead. TRUE on a record with an end draws the arrowhead at the end of its lane's last segment (still ongoing). Default NULL: no arrow.

  • lane: Splits a row into lanes. Records where it is empty draw on the main lane at full height, with the ticks, the line and the events; each other level draws a thin lane above it, in level order, so a row grows with its lanes (a drug per lane above the response). Without any main-lane record the lanes are even and the overlays run across the row; an event with a lane draws on its lane. Default NULL: one lane.

  • lane_full: Logical. A lane whose records have it TRUE is a full bar: the first such lane is the main lane, the others draw below it at full height, with their own events and open end (a second response assessment). With more than one bar each is named at its left, the main one in bold. Default NULL: thin lanes only.

  • seg_style: How a record draws, by value: "dashed" a dashed line (a skipped period), "hollow" an outlined box (a delay), "dot" a ring at its start (one administration), "step" a small down step at its start (a dose cut), "outline" filled with a dark edge (a serious event), "thinner" a lower bar (a reduced dose), "hairline" a 1px line (a dose of zero). Anything else draws solid. A dot or a step needs no end. Default NULL: all solid.

  • event_tag: Short text, per event. An event with a value draws as that text in a small box just after its position ("AE") instead of its shape. A shape level whose events all carry a tag shows a box in the legend. Two tags on one lane that would overlap split around the lane's centre line, the later one above (on the same day, the later tag group's). Default NULL: shapes only.

  • event_tag_group: The group of a tagged event ("Treatment discontinuation", "End of study"). Each group is a legend group of its own, titled by the value, in the column's level order. The first group's tags draw as outlined boxes, the others' inverted: an ink box with light text. For a factor the first group is its first level, even when no event has it. An item named ": " shows as under its group. Default NULL: one group.

  • tip: The tooltip of a record, segment or event, as is: its text up to the first " · " heads the card, each further part is a line. An empty value keeps the computed tooltip (label, level, span, fields). Default NULL: the computed tooltip.

  • x_unit: Word written before the first label of the column's axis ("Day" reads "Day 0"). Only on a numeric axis; a date axis names its own dates. Default NULL: numbers only.

  • x_limits: The axis from and to, as c(1, 180); NA at either end is the data's. Dates as "2024-01-01". A bar across a limit is cut at it, with the open caret at the right; bars, ticks and events wholly outside are not drawn. Tooltips keep the records' own values. A prepare script can set the same as the attribute blockr_domain of the start column, which this overrides end by end. Default NULL: the data's range.

  • x_days: The axis reads in study days: "D1", "D20", ..., day 1 always a tick, and no day 0, so an x at or below 0 reads as the day before (x = 0 is "D-1"), as ADaM counts. Only on a numeric axis; the hover reads the same way. Default: FALSE.

  • lane_size: Height of the lanes above the main lane: "sm" 5px with a 3px line, "md" 9px with a 5px bar whose free ends round, for rows where the lanes carry the story (a drug per lane). One of "sm", "md". Default: "sm".

  • track: A grey track behind the main lane and the full bars, as a bar column draws it. Off: the bars stand on the surface. Thin lanes never have one. Default: FALSE.

  • overlap: How records that overlap on one lane draw. "draw": each its own bar, the later over the earlier. "worst": cut into pieces, each coloured by the highest colour level active there (legend order), so one stripe shows the worst stretch. One of "draw", "worst". Default: "draw".

  • inner_overlap: How a lane's records that overlap draw on the inner rows of a nested table. "same": as overlap says. "stack": each record whole, a record that overlaps an earlier one on a copy of the lane under it, so two episodes of one event read as two bars. Outer rows keep overlap. One of "same", "stack". Default: "same".

  • parent_lanes: With group_rows = "summary", an outer row draws its rows' lanes, events and open ends as an inner row does. Off: the outer row draws the main lane's bars only. Default: FALSE.

  • strip: Text of one box in its lane's hover strip; lines split at a newline. Pointing at a lane shows its boxes in time order, a hollow record's box marked late and a dashed one's as skipped. A strip record needs only a start. Default NULL: no strip.

type = "pair"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • x: Start value, drawn as a hollow diamond. Required.

  • xend: End value, drawn as a dot. Required.

  • x_func: How x is read per group. One of "identity", "mean", "median", "min", "max". Default: "identity".

  • xend_func: How xend is read per group. One of "identity", "mean", "median", "min", "max". Default: "max".

  • ref_min: A number or a column: the low end of a shaded reference range. An xend outside the range is drawn open. Default NULL: no range.

  • ref_max: A number or a column: the high end of the range. Default NULL: no range.

  • x_lines: Dashed reference lines, as the chart's x_lines. Default NULL: no line.

  • linetype: Non-first levels of this column are drawn dashed. Default NULL: all solid.

  • color: Color split, at most 15 levels. Default NULL: no color split.

type = "expr"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • expr: R expression evaluated in dplyr::summarise() per row group. A numeric result is a number cell, anything else text. Required.

type = "custom"

  • name: Column header. Default NULL: auto ("Rows", "Mean AGE").

  • facet: Repeats the column once per level, on one scale. At most 15 levels, 300 for tiles. Default NULL: no facet.

  • show: The mark; NULL reads it off the result's columns. One of "bar", "number", "dumbbell", "box", "pointrange", "text". Default NULL: read off the result.

  • fn: A function of d, the rows grouped by table row. Returns a data frame or named vector with columns among value, from, to, lo, q1, mid, q3, hi, text, plus at most one color column. Required.

  • id: A count prints "n (pct%)" with N the distinct values of this column. Default NULL: count rows.

Shadings

Each entry of shadings is a list with these keys.

  • mode: "diverging" centers on 0, "sequential" ramps two colors, "bar" draws a data bar in the cell. An unknown mode is an error. One of "diverging", "sequential", "bar". Default: "diverging".

  • columns: Numeric columns the rule paints. Default NULL: every numeric column no earlier rule claims.

  • domain: c(low, high) the colors span, e.g. c(-1, 1) for correlations. Default NULL: the data range; diverging is symmetric around 0.

See Also

new_chart_block(), as_annotated_df()

Examples

# Records: the input's rows, two columns, filtering on a click
new_table_block(columns = c("Species", "Sepal.Length"), drill = "auto")

# Groups: per species a row count, a mean and a box of petal lengths
new_table_block(
  layout = "groups", by = "Species",
  summaries = list(
    list(type = "simple", func = "count"),
    list(type = "simple", func = "mean", col = "Sepal.Length"),
    list(type = "dist", col = "Petal.Length")
  )
)

# The same as cards
new_table_block(
  layout = "groups", look = "cards",
  summaries = list(list(type = "simple", func = "count"))
)

# Variables: a Table 1, one column per species
new_table_block(layout = "variables", by = "Species")

if (interactive()) {
  blockr.core::serve(
    new_table_block(layout = "groups", by = "Species",
                    summaries = list(list(type = "simple", func = "count")),
                    drill = "auto"),
    data = list(data = iris)
  )
}

A block's exhibit

Description

What a block's downloads write: its rows and, when the browser drew the block, the picture.

Usage

new_viz_exhibit(
  data,
  picture = NULL,
  render = NULL,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  kind = c("table", "chart"),
  meta = list()
)

Arguments

data

An annotated data frame (as_annotated_df()): the rows as the block shows them, with their cell formats, colours and groups.

picture

A chart_capture: the block as the browser drew it, or NULL.

render

An object that html_exhibit() and pptx_add_exhibit() draw better than data alone (the groups table with its marks, cards), or NULL.

title, subtitle, caption

The resolved text, or NULL.

kind

"table" or "chart".

meta

A named list: dataset (the first part of the file name), digits (the number format the screen rounds to), collapsible and sortable (for the web page), source (the frame the download footer's provenance is read from, when data was built for the export).

Value

A viz_exhibit.

See Also

register_viz_exporter()

Examples

tbl <- summary_table(iris, vars = "Sepal.Length", by = "Species")
ex <- new_viz_exhibit(tbl, title = "Sepal length", kind = "table",
                      meta = list(dataset = "iris"))
exhibit_kind(ex)
exhibit_titles(ex)$title
exhibit_data(ex)

Add an Exhibit's Slides to an Open Deck

Description

The paginating half of write_exhibit_pptx(), without the file: it takes an officer::read_pptx() document, appends one slide per page of the table, and returns the document. Column widths, font step-down, row and column splits, repeated header bands and ⁠(2 of 8)⁠ page titles all happen here, so a caller assembling its own deck gets the same slides as a single-table download.

Usage

pptx_add_exhibit(doc, x, ...)

## Default S3 method:
pptx_add_exhibit(
  doc,
  x,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  template = NULL,
  layout = NULL,
  master = NULL,
  top = NULL,
  max_rows = "auto",
  max_cols = "auto",
  min_font_size = NULL,
  ...
)

Arguments

doc

An rpptx document from officer::read_pptx().

x

A data frame, an as_annotated_df()-coercible table object, or a flextable built by static_table(), which carries its source frame and so can still be paged. A flextable from anywhere else is placed whole on one slide.

...

Passed to static_table().

title, subtitle, caption

Slide title, table subtitle and footnote. NULL or "" omits each. The title goes into the layout's title placeholder when the template has one and into the table's own header otherwise.

template

Path to a reference .pptx, or NULL (default) to resolve one as described above.

layout, master

Layout and master to add slides on. NULL (default) picks "Title and Content" when the deck has it, else the first layout.

top

Distance from the top of the slide to the table, in inches. NULL (default) measures it from the layout's own title placeholder, so a wrapped title cannot land on the table.

max_rows

How a table too tall for its slide is handled. "auto" (default) carries it onto further slides, cutting where the measured height of the rendered rows runs out of slide. A number cuts every max_rows input rows instead. NULL never splits. Every page repeats the title (marked ⁠(2 of 3)⁠), the header band and the footnote, and a section carried across a break repeats its heading marked (continued). Column widths are measured once on the whole table. A break never leaves one or two rows of a section at the top of a slide.

max_cols

How a table too wide for its slide is handled, once the font has stepped down to min_font_size and the data cells still do not fit their own longest word. "auto" (default) deals the columns over several sets of slides, each repeating the row stub; a set is a whole number of spanner groups. A number puts at most that many data columns on a slide. NULL never splits and squeezes the columns as far as they go. Set getOption("blockr.viz.ft_header_break_tol") (default 0, off) to also deal the columns when a header word keeps less than that share of itself.

min_font_size

Points. The floor for the font step-down. NULL (default) resolves it, first hit wins, from the board's exhibit_min_font_size option (new_exhibit_font_option()), then getOption("blockr.viz.ft_min_font_size"), then 11pt. A table that does not fit at the floor is split rather than shrunk past it, and signals a blockr_exhibit_split message naming the size that would have kept it whole.

Value

The document, with the exhibit's slides appended.

What the caller owns

The options that size and typeset the table (blockr.viz.ft_fit_width, blockr.viz.ft_font) are not set here. A deck sets them once around all of its slides, from its own template. write_exhibit_pptx() sets them for the single-table case. A template passed here only supplies the title's point size and typeface, used to measure where the title ends.

See Also

write_exhibit_pptx(), static_table()

Examples

doc <- officer::read_pptx()
doc <- pptx_add_exhibit(doc, head(iris, 20), title = "Iris")
length(doc)

Register blockr.viz blocks

Description

Registers the blockr.viz render and shaper blocks with blockr so they appear in the block-adder and the assistant block universe.

Usage

register_viz_blocks()

Value

Invisibly, the result of blockr.core::register_blocks().

Examples

register_viz_blocks()

Register a download format

Description

Register a download format

Usage

register_viz_exporter(
  format,
  label,
  fun,
  ext = format,
  accepts = function(x) TRUE,
  needs = character(),
  order = 50
)

Arguments

format

A short id: the download output is ⁠dl_<format>⁠.

label

The menu text ("Excel").

fun

A function ⁠(exhibit, file)⁠ that writes the file. It reads the exhibit with the exhibit-accessors only.

ext

The file extension.

accepts

A function of an exhibit: whether this format can write it (Image needs a picture). A block's menu asks it about a probe of the exhibit: the kind and the picture are the exhibit's, and so is whether it has a render object, but the data and the render object themselves are stand-ins, since building them is the download's work.

needs

Packages the format needs; it is left out of the menu when one is not installed.

order

The position in the menu, smallest first.

Value

format, invisibly. A format registered again replaces the old.

See Also

new_viz_exhibit()

Examples

# A CSV download, offered by every block from now on
register_viz_exporter(
  "csv", "CSV",
  function(exhibit, file) {
    utils::write.csv(exhibit_data(exhibit), file, row.names = FALSE)
  }
)

Report Call for a Block's Printed Result

Description

How a block's result is printed in a rendered document (a blockr.outline report or deck). Returns a call over var, the variable the generated script binds the block's result to, such as blockr.viz::static_table(tbl1), or NULL when the bare result prints as is. The call is self-qualified and holds only literal values, since consumers deparse it into the document. The chart block has no method: a document carries the picture the browser captured (see chart_capture_ids()).

Usage

report_call(x, var, ...)

## Default S3 method:
report_call(x, var, ...)

## S3 method for class 'table_block'
report_call(x, var, ...)

Arguments

x

A block object.

var

The variable name (string) holding the block's result in the generated document.

...

Reserved.

Value

A call, or NULL for the bare print.

Examples

report_call(new_table_block(), "tbl1")
report_call(new_chart_block(), "chart1")

Static Renderer for Any Block Result

Description

The print routine a rendered report or deck applies to a block's result. Objects that already print as themselves (a flextable, a gt table, a ggplot, an htmlwidget, ready-made HTML) come back untouched. A data frame or any object with an as_annotated_df() method (a composer table, a gtsummary table, ...) is rendered through static_table(). Anything else comes back untouched.

Usage

static_exhibit(x, ...)

Arguments

x

A block result: a data frame, an as_annotated_df()-coercible table object, or anything else.

...

Passed to static_table() when x is rendered as one.

Details

Data frames above getOption("blockr.viz.static_exhibit_max_rows") (2000) rows fall back to the bare print.

Value

A flextable, or x unchanged.

See Also

static_table(), as_annotated_df()

Examples

# an annotated data frame becomes the styled static table ...
static_exhibit(summary_table(iris, vars = "Sepal.Length", by = "Species"))

# ... anything else is returned as-is
identical(static_exhibit(1:3), 1:3)

A Summarize Table as a Printable Exhibit

Description

The groups layout of the table block (new_table_block(layout = "groups")) rebuilt outside Shiny, as an object a report, a deck or a download can render. The block's own result is only its input data; this puts the table itself into a document.

Usage

static_summarize_table(data, ...)

Arguments

data

A data frame (or as_annotated_df()-coercible object), the table's input.

...

The groups layout's arguments, as in new_table_block() (by, summaries, sort_by, top_n, title, ...). The single ranked bar's arguments (group, func, value, color, facet, ...) are read as the column list they map to.

Details

html_exhibit() gives the same HTML table the app draws, and pptx_add_exhibit() paints it and places it on as many slides as it needs. Both read one cell model, computed here.

On a slide the exhibit is a picture, because PowerPoint's table cells hold text runs only and a distribution glyph cannot live in one. The text is therefore not selectable or editable on those slides. A plain display table keeps static_table().

Value

An object of class summarize_exhibit.

See Also

pptx_add_exhibit(), html_exhibit()

Examples

ex <- static_summarize_table(
  mtcars, by = "cyl",
  summaries = list(
    list(type = "simple", func = "count", show = "bar", name = "Cars"),
    list(type = "dist", col = "mpg", show = "box",
         summary = "median_q1_q3", whiskers = "p10_p90", name = "MPG")
  )
)
ex

Flextable Renderer for Annotated Data Frames

Description

Renders an annotated data frame as a styled flextable, the static table output for report and deck rendering (quarto pptx, docx).

Usage

static_table(
  data,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  na_rep = "—",
  font = getOption("blockr.viz.ft_font", "Inter"),
  font_size = getOption("blockr.viz.ft_font_size", 13),
  font_color = "#444444",
  indent_width = 20,
  first_col_width = 5.65,
  other_cols_width = 3.5,
  fit_width = getOption("blockr.viz.ft_fit_width", NULL),
  col_widths = getOption("blockr.viz.ft_col_widths", "measured"),
  cell_padding = NULL,
  auto_width = FALSE,
  continued = FALSE,
  header_bg = getOption("blockr.viz.ft_header_bg", viz_palette("bands")),
  pptx_left = 0.4,
  pptx_top = 1.1
)

Arguments

data

A data frame (or an object with an as_annotated_df() method, e.g. a composer table, coerced on entry).

title, subtitle, caption

Table title / subtitle (header lines) and caption (footer line). NULL (default) fills from the annotated df's label / subtitle / caption attributes; "" suppresses.

na_rep

Character. Text for missing (NA) cells. Defaults to an em dash.

font, font_size, font_color

Base typography, applied to all parts. font_size is in points and defaults from getOption("blockr.viz.ft_font_size"), 13 unset. font defaults from getOption("blockr.viz.ft_font"), which a theme sets (exhibits = list(ft_font = ...)) and which the pptx export sets from the reference deck's font scheme.

indent_width

Points of left padding per .indent level (section headers indent at their nesting depth with the same step).

first_col_width, other_cols_width

Column widths in inches, used unless fit_width or auto_width is set. Defaults fit the 13.33in widescreen template.

fit_width

Optional total table width in inches (usually the slide's usable content width). The columns are distributed to fill it exactly (col_widths says how). Defaults from getOption("blockr.viz.ft_fit_width"), which the pptx / docx render sets from the reference template. Unset for html / pdf.

col_widths

How fit_width is split, "measured" (default) or "even". Measured gives every column what its own text needs at the current font: no cell wraps and no header breaks inside a word when the slide can hold them, and the rest goes to the row stub (at most getOption("blockr.viz.ft_stub_share"), 0.3, of the width while the data columns are short of their full headers). When the slide cannot hold them all, the columns are filled to a common level, from their longest word toward their whole text. Even gives the stub first_col_width capped at half the slide and splits the remainder equally. A numeric vector of widths (one per column, stub first) is used as given; write_exhibit_pptx() uses it to give every page of a split table the same widths. Defaults from getOption("blockr.viz.ft_col_widths").

cell_padding

Points of left and right padding per cell, or NULL (default) for the flextable default of 5. Set automatically to a tighter value when a table cannot fit any other way.

auto_width

Logical. TRUE runs flextable::autofit() instead of the manual widths.

continued

Logical. TRUE marks the section headings this table opens with as (continued), for a page of a split table.

header_bg

Header band colors, keyed on the column-group structure the annotated df carries. A color vector (hex or R color names):

  • Named entries pin a group. The name is a by-level value (the spanner top for a nested by, else the data-column name), and ".stub" pins the row-stub header.

  • Unnamed entries are the cycle pool for the remaining, unpinned groups, in order.

  • The two mix: c(.stub = "#EEE", Placebo = "grey", "#33D6F1").

Defaults from getOption("blockr.viz.ft_header_bg"); unset (or NULL / "none") leaves the header unfilled.

pptx_left, pptx_top

Slide placement in inches, stashed as attributes on the result for the officer-based pptx pipeline. Inert under the quarto render.

Details

Structure comes from the annotated-df contract (shared with the table view and write_annotated_xlsx()): .label is the row stub, ⁠.group<k>_level⁠ runs and .variable_label blocks become bold section-header rows merged across the table width, .indent / .strong / .emph style rows, Top||Leaf column names become a merged spanner header row, and attr(col, "label") carries the leaf header text ("\n" is a line break). The other identity columns are ignored here.

Columns can carry emphasis, the column analogue of the row flags: attr(col, "strong") / attr(col, "emph"). When any column is flagged, the header band follows an emphasis ramp (normal light gray, emph dark gray and italic, strong an accent) and header_bg is ignored.

Value

A flextable object (with pptx_left / pptx_top attributes).

See Also

as_annotated_df(), write_annotated_xlsx(), exhibit-options for everything the renderer reads from options()

Examples

tbl <- summary_table(iris, vars = "Sepal.Length", by = "Species")
static_table(tbl, title = "Sepal length by species")

Summary Table – Multi-Variable Descriptive Summary (Table 1)

Description

Aggregate a flat data.frame into the wide annotated data frame the blockr table renderers consume directly: one formatted column per by-group level (each cell baked from its statistic at produce time, so the renderer does no arithmetic), dotted identity / structure columns for the row-side hierarchy (the ARD-named ⁠.group<k>⁠ / ⁠.group<k>_level⁠ pairs for sections, .variable / .variable_level / .variable_label for the leaf rows – section and variable headers are synthesized by the renderer from value runs, never materialized as rows), Top||Leaf spanner column names for length-2 by, and per-group "<group>\nN = <n>" column labels. This is the same annotated-df contract that composer emits via as_annotated_df(), so the table block treats both identically. The identity pairs are what a drill-down filters on; a level row asserts "the source rows where .variable == .variable_level".

Usage

summary_table(
  data,
  vars = character(),
  sections = character(),
  by = character(),
  stats = "mean_sd",
  add_overall = FALSE,
  overall_label = "Total",
  subject_var = NULL,
  indent_details = TRUE,
  nest_hierarchies = FALSE,
  missing = "drop"
)

Arguments

data

A flat data.frame.

vars

Character vector of variables to summarise. Each becomes a section in the output.

sections

Optional character vector of outer section columns from data. Used for nested row-side hierarchy (e.g. ⁠sections = "AESOC", vars = "AEDECOD"⁠).

by

Character vector of length 0-2. Values become the .group dimension. Length-2 produces pipe-delimited nested group keys consumable by gt::tab_spanner_delim("|") after the renderer spreads .group to columns.

stats

Character vector of stat keys controlling which rows / templates are emitted for numeric variables (the underlying numbers are always all computed). Any combination of "n", "n_pct" (non-missing n and % of group rows), "mean", "sd", "mean_sd", "median", "median_q1_q3", "q1_q3", "min_max"; rows follow the order given. A single key gives one row per variable, several give one row per stat. The legacy presets "compact" (= "mean_sd") and "expanded" (= c("n", "mean", "sd", "median", "q1_q3", "min_max")) are still accepted. Default "mean_sd".

add_overall

Logical. If TRUE, append an extra .group whose rows are computed on the unsplit data (ignoring by). Matches gtsummary::add_overall().

overall_label

Character. .group value for the overall rows when add_overall = TRUE. Default "Total".

subject_var

Optional subject-identifier column for distinct-subject counts (for categorical n_pct). If NULL, rows are counted instead.

indent_details

Logical, default TRUE. When TRUE, detail rows (stat rows for expanded numerics, category-level rows for categoricals) are tagged with .indent = 1. When FALSE, no .indent column is emitted.

nest_hierarchies

Logical, default FALSE. Advanced option. When TRUE, adjacent categorical entries in vars that form a functional dependency in data are rendered as a row-side drill-down. v1 supports 2-level hierarchies only.

missing

Missing values of a categorical variable, of by and of sections: "drop" (default) gives them no row or column, "level" shows them as "(Missing)". Numeric variables are summarised without their missing values either way. A drill_source() claim on the "(Missing)" level selects the rows whose value is missing.

Details

Numeric variables emit one row per selected stats key (mean/sd/median/...), categoricals one row per level as ⁠n (%)⁠, and logicals a single TRUE-count row (the pharma flag convention). Digit precision is fixed per statistic and applied here, at aggregation time.

Value

A wide annotated data frame: dotted identity / structure columns plus one formatted character column per by-group level, each carrying a label attribute holding its "<group>\nN = <n>" header. Consumed by new_table_block(), html_exhibit() and any renderer that understands the annotated-data-frame convention.

See Also

as_annotated_df()

Examples

# Simple demographics
summary_table(
  iris,
  vars = c("Sepal.Length", "Species"),
  stats = "mean_sd"
)

# Any stat combination, split by a grouping column
summary_table(
  mtcars,
  vars = c("mpg", "hp"),
  by = "cyl",
  stats = c("n_pct", "median_q1_q3", "min_max"),
  add_overall = TRUE
)

The Table Block as a Printed Table

Description

What new_table_block() puts into a rendered report or deck: the table as the block shows it, as an annotated data frame for static_exhibit() to typeset. The rowname comes first, then columns; numbers are printed in the block's format exactly like the screen, and unit heads the numeric columns; cells shaded by a diverging or sequential rule carry their colours as ⁠.bg:⁠ / ⁠.fg:⁠ columns, which static_table() and the HTML table paint. Colour source columns are left out. In-cell bars are not drawn.

Usage

table_exhibit(
  data,
  rowname = NULL,
  columns = NULL,
  shadings = list(),
  format = "number",
  unit = NULL,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  ...
)

Arguments

data

The table block's input: a data frame or an as_annotated_df()-coercible table object.

rowname, columns, shadings, format, unit

As in new_table_block().

title, subtitle, caption

Table text, with the block's three tiers: NULL takes the input's label / subtitle / caption attribute, "" shows none, any other string is a title template resolved against data.

...

Old argument names, translated with a warning: value (now columns), digits (now format), and group with summaries, the aggregation the table block no longer does.

Details

The block's report_call() emits ⁠blockr.viz::static_exhibit(blockr.viz::table_exhibit(<var>, ...))⁠ with its own settings, so blockr.outline needs nothing table-specific.

Value

An annotated data frame, with label, subtitle and caption attributes carrying the resolved text.

See Also

new_table_block(), static_exhibit(), report_call()

Examples

table_exhibit(
  data.frame(term = "A", times_more = 3.81427, ci_low = 2.70123),
  format = 2L, title = "Area effect"
)

A table block's own gear

Description

A block built on the table (a swimmer, an AE timeline) shows its own settings instead of the whole table's: its tabs, its sections, its rows. Pass the result as gear to new_table_block(). Table settings the gear does not name have no row but keep working: from code, and through a word in the titles.

Usage

table_gear(
  tabs,
  columns = list(),
  groups = character(),
  clauses = character(),
  info = NULL,
  open = NULL,
  deps = list(),
  pick_by = NULL,
  pick_skip = character(),
  sort_value = NULL,
  columns_note = NULL
)

Arguments

tabs

A named list, one element per tab in tray order. An element is a character vector of keys (one section, titled as the tab) or a named list of character vectors (sections and their keys).

columns

A named list of the columns the checklist offers, in order: each a summary as in summaries of new_table_block(), without name (the list name) and with an optional on (default TRUE), whether a new block shows it. The block shows the ticked ones, first, then its other summaries.

groups

The columns the rows may be grouped by, for the "group" row: a character vector, named by the labels the pick shows.

clauses

A named character vector: per setting, the clause it adds to the subtitle when ticked "In the subtitle" (c(doses = "doses shown as {@doses}")), in sentence order.

info

A function of the block's input (a data frame or a dm), called again when it changes. What it returns goes to the browser as derived.gear.info, for a package's own rows (which tables and columns a block found). An error gives NULL.

open

The tab the tray opens at when the prepare script fails (a table or column missing), or NULL.

deps

HTML dependencies the block's page needs, the script of a package's own rows among them.

pick_by

The column naming the table's outer rows (a patient id). Set, the "columns" row is a select of several picks: columns first, then every column of the prepared data with at most one value per value of pick_by, named by its label, each a field summary. A picked column the data no longer has is left out of the table. Columns whose name starts with a dot, and those of by, are not offered.

pick_skip

Columns of the prepared data the "columns" row does not offer (the block's own: a swimlane's start and end).

sort_value

The name of a value the prepare script declares, which the "columns" row sets to its first pick (the name in columns, else the data column's name; "" with none), so the script can order the rows by the first column.

columns_note

A line under the "columns" row.

Details

A key in tabs is one of

  • a setting of the table ("by", "sort_by", "search", ...), or a shorthand: "sort" (sort_by, sort_dir), "titles" (title, subtitle, caption, and the "In the subtitle" ticks when clauses is given) or "drill" (drill, drill_target, drill_table);

  • a value the prepare script declares (doses <- factor(...) #| select()), drawn as an ordinary row that writes script_values;

  • "columns": a checklist of columns; with pick_by, a select of several picks instead, in the order picked (a drag reorders them), that also offers the prepared data's columns with one value per row;

  • "group": a pick among groups (or none) for the outer column of a nested by, which groups the rows;

  • a key with an editor registered in the browser (Blockr.viz.gear.editors[key]), for a package's own row.

A key that resolves to none of these has no row.

Value

A viz_table_gear object.

Examples

table_gear(
  tabs = list(
    Rows = c("by", "sort", "columns"),
    Titles = "titles"
  ),
  columns = list(
    Weeks = list(type = "simple", func = "max", col = "weeks"),
    Age = list(type = "field", col = "AGE", on = FALSE)
  )
)

The summaries a new block with this gear shows

Description

The ticked columns of a table_gear(), in order, then other.

Usage

table_gear_summaries(gear, other = list())

Arguments

gear

A table_gear().

other

Summaries the checklist does not offer (the block's own column, a swimlane).

Value

A list of summaries for summaries of new_table_block().


Hand records to a table block's data view

Description

Called at the end of a table block's prepare script (or a function it calls) on the frame the script returns. The block then offers a table tool, left of its download button, that opens records under the table, narrowed to the rows a click selects: each clicked column that records carries filters them. The download menu's Data section writes them as CSV and Excel.

Usage

viz_records(x, records, label = NULL)

Arguments

x

The frame the prepare script returns.

records

A data frame, or NULL for none.

label

What the records are, for the view and the download menu ("Adverse events"). NULL: "Records".

Value

x, with the records attached.

Examples

rows <- data.frame(USUBJID = c("01", "02"), n = c(2L, 1L))
ae <- data.frame(USUBJID = c("01", "01", "02"),
                 AETERM = c("HEADACHE", "NAUSEA", "RASH"))
x <- viz_records(rows, ae, "Adverse events")

Write an annotated data frame to a styled Excel (.xlsx) file

Description

Renders an annotated data frame to an Excel worksheet that keeps the table's structure: row indentation (.indent becomes the cell indent), bold rows (.strong), and two-level column spanners (Top||Leaf becomes merged header cells). The same frame drives the blockr.viz table renderer.

Usage

write_annotated_xlsx(
  x,
  file,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  sheet = "Table",
  digits = NULL
)

Arguments

x

An annotated data frame, or any object with an as_annotated_df() method (e.g. a composer composed_table), which is coerced first.

file

Path to write the .xlsx to.

title

Optional title, written merged-and-bold above the table.

subtitle

Optional subtitle, written merged-and-italic under the title.

caption

Optional caption / footnote line, written italic below the table.

sheet

Worksheet name.

digits

Optional number format, the table block's format. A number of decimals gives every numeric data column that cell number format ("0.00" for digits = 2): the cell keeps the full value and displays it rounded. "number" shows two decimals on columns that hold fractions and leaves whole-number columns in the general format. "compact" (1.2K, 3.4M) and "percent" (12.3%) format every numeric column. NULL (default) writes every number in the general format.

Details

Input is the annotated-data-frame contract:

  • .label is the row-stub (first) column; .indent is the Excel cell indent level; .strong rows are bold.

  • ⁠.section_1, ..., .section_k⁠ become bold section-header rows merged across the table, interleaved at each section restart, as in the HTML renderer. These and any other dot-prefixed columns are not exported as data columns.

  • a .strong row, or a row above a deeper .indent, whose data cells are all empty is a heading: bold and merged across the table.

  • data columns carry their pre-formatted strings. A name with a "||" ("Placebo||CAT1") is a two-level spanner: the part before the "||" becomes a merged top header cell; attr(col, "label") ("Placebo\nN = 86") is the leaf header text.

The header is frozen, bordered, and bold; numbers right-align, the stub left-aligns. Only openxlsx is needed.

Value

file, invisibly.

See Also

as_annotated_df(), new_table_block()

Examples

f <- tempfile(fileext = ".xlsx")
write_annotated_xlsx(
  summary_table(iris, vars = "Sepal.Length", by = "Species"),
  f,
  title = "Sepal length by species"
)
unlink(f)

Write an Exhibit to a Self-Contained HTML File

Description

The HTML sibling of write_annotated_xlsx() and write_exhibit_pptx(). The table is drawn by html_exhibit() inside a minimal document shell that carries the title, subtitle and caption.

Usage

write_exhibit_html(
  x,
  file,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  default_expanded = TRUE,
  collapsible = TRUE,
  sortable = TRUE,
  ...
)

Arguments

x

A data frame, an as_annotated_df()-coercible table object, or an exhibit that renders itself, such as a summarize_exhibit from static_summarize_table().

file

Path to write the .html to.

title, subtitle

Document heading and its muted second line. NULL or "" omits each.

caption

Trailing footnote, rendered under the table.

default_expanded

Logical. TRUE (default) opens every section, since the page scrolls and has no height to budget. FALSE opens the table at its section rows.

collapsible, sortable

Logical. Whether the saved page keeps the collapse chevrons and the click-to-sort headers (both TRUE by default).

...

Passed to html_exhibit().

Details

The file is self-contained: no Shiny, no CDN, no sidecar folder. The display table inlines its own ⁠<style>⁠ and ⁠<script>⁠, and the dependencies of a renderer such as the summarize table are read off disk and written into the document. Section collapse and column sorting work in the saved file, offline.

Value

file, invisibly.

See Also

write_exhibit_pptx(), write_annotated_xlsx(), html_exhibit()

Examples

f <- tempfile(fileext = ".html")
write_exhibit_html(
  summary_table(iris, vars = "Sepal.Length", by = "Species"),
  f,
  title = "Sepal length by species"
)
unlink(f)

Write an Exhibit to a PNG

Description

The exhibit as one image: what pptx_add_exhibit() places on a slide, without the slide. A summarize table is as tall as it is long (nothing is paged); a ggplot is drawn at the size the plot asks for.

Usage

write_exhibit_png(
  x,
  file,
  width_in = NULL,
  res = getOption("blockr.viz.paint_res", 300),
  ...
)

## Default S3 method:
write_exhibit_png(x, file, width_in = NULL, res = 300, ...)

## S3 method for class 'summarize_exhibit'
write_exhibit_png(
  x,
  file,
  width_in = NULL,
  res = getOption("blockr.viz.paint_res", 300),
  ...
)

## S3 method for class 'gg'
write_exhibit_png(
  x,
  file,
  width_in = NULL,
  res = getOption("blockr.viz.paint_res", 300),
  ...
)

Arguments

x

A summarize_exhibit from static_summarize_table(), or a ggplot.

file

Path to write the .png to.

width_in

Image width in inches. NULL (charts) keeps the plot's own.

res

Pixels per inch.

...

Passed to the renderer.

Details

The image is a re-render from the cell model the browser gets, not a screenshot.

Value

file, invisibly.

See Also

static_summarize_table(), write_exhibit_pptx()

Examples

ex <- static_summarize_table(
  mtcars, by = "cyl",
  summaries = list(list(type = "simple", func = "count", show = "bar"))
)
f <- tempfile(fileext = ".png")
write_exhibit_png(ex, f)
unlink(f)

Write an Exhibit to a PowerPoint Deck

Description

The pptx sibling of write_exhibit_html() and write_annotated_xlsx(): the annotated data frame typeset by static_table() and placed on a slide of the house template. A table too tall for one slide is carried over onto as many as it needs, each repeating the header (see max_rows). A table too wide has its columns dealt over several slides (see max_cols). The table is a native PowerPoint table: every cell is real text an editor can retype, restyle and recolour.

Usage

write_exhibit_pptx(
  x,
  file,
  title = NULL,
  subtitle = NULL,
  caption = NULL,
  template = NULL,
  max_rows = "auto",
  max_cols = "auto",
  min_font_size = NULL,
  ...
)

Arguments

x

A data frame or as_annotated_df()-coercible table object.

file

Path to write the .pptx to.

title, subtitle, caption

Slide title, table subtitle and footnote. NULL or "" omits each. The title goes into the layout's title placeholder when the template has one and into the table's own header otherwise.

template

Path to a reference .pptx, or NULL (default) to resolve one as described above.

max_rows

How a table too tall for its slide is handled. "auto" (default) carries it onto further slides, cutting where the measured height of the rendered rows runs out of slide. A number cuts every max_rows input rows instead. NULL never splits. Every page repeats the title (marked ⁠(2 of 3)⁠), the header band and the footnote, and a section carried across a break repeats its heading marked (continued). Column widths are measured once on the whole table. A break never leaves one or two rows of a section at the top of a slide.

max_cols

How a table too wide for its slide is handled, once the font has stepped down to min_font_size and the data cells still do not fit their own longest word. "auto" (default) deals the columns over several sets of slides, each repeating the row stub; a set is a whole number of spanner groups. A number puts at most that many data columns on a slide. NULL never splits and squeezes the columns as far as they go. Set getOption("blockr.viz.ft_header_break_tol") (default 0, off) to also deal the columns when a header word keeps less than that share of itself.

min_font_size

Points. The floor for the font step-down. NULL (default) resolves it, first hit wins, from the board's exhibit_min_font_size option (new_exhibit_font_option()), then getOption("blockr.viz.ft_min_font_size"), then 11pt. A table that does not fit at the floor is split rather than shrunk past it, and signals a blockr_exhibit_split message naming the size that would have kept it whole.

...

Passed to static_table().

Value

file, invisibly.

The template

The reference deck supplies the slide size, layouts, title placeholder and theme fonts. It is resolved, first hit wins, from template, getOption("blockr.viz.pptx_template"), getOption("blockr.outline.template"), then blockr.outline's bundled widescreen default when installed. With none of them, officer writes its own stock deck. The template's content width sizes the table's columns, and its theme's body font is the table's font unless blockr.viz.ft_font is set.

See Also

write_exhibit_html(), write_annotated_xlsx(), static_table(), exhibit-options for the options that tune the fit

Examples

f <- tempfile(fileext = ".pptx")
write_exhibit_pptx(
  summary_table(iris, vars = "Sepal.Length", by = "Species"),
  f,
  title = "Sepal length by species"
)
unlink(f)