| Title: | Lightweight Tables via JSON Specs and JavaScript |
|---|---|
| Description: | A lightweight grammar of tables. Build a table by declaring a JSON spec (titles, spanners, row groups, footnotes, formatting functions, etc.); a tiny vanilla JavaScript runtime builds the HTML table from the spec on page load. Cells can hold inline plots (error bars, dot plots, mini line and bar charts) drawn as SVG in the browser from the numbers alone. Tables can optionally be made interactive (sorting, searching, filtering, pagination, column hiding, expandable row detail, and CSV download) via a separate extension loaded only when requested. No 'sass', no 'V8', no 'htmlwidgets' — just base R and 'xfun' ('htmltools' is used only for the optional Shiny binding and for embedding tables in other HTML output). |
| Authors: | Yihui Xie [aut, cre, cph] (ORCID: <https://orcid.org/0000-0003-0645-5666>, URL: https://yihui.org) |
| Maintainer: | Yihui Xie <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.5.31 |
| Built: | 2026-11-20 00:25:00 UTC |
| Source: | https://github.com/yihui/lt |
lt_tbl to HTMLEmits the CSS+JS runtime and a script block carrying the table's JSON spec. Multiple tables on the same page only need the runtime once.
## S3 method for class 'lt_tbl' format(x, fragment = TRUE, inline_assets = TRUE, assets = TRUE, ...)## S3 method for class 'lt_tbl' format(x, fragment = TRUE, inline_assets = TRUE, assets = TRUE, ...)
x |
An |
fragment |
If |
inline_assets |
If |
assets |
Which runtime assets to include: |
... |
Reserved for future use. |
A character scalar containing HTML.
tbl = lt(ToothGrowth[1:3, ]) # an HTML fragment with the assets inlined html = format(tbl) # a full page, linking the assets instead of inlining them format(tbl, fragment = FALSE, inline_assets = FALSE)tbl = lt(ToothGrowth[1:3, ]) # an HTML fragment with the assets inlined html = format(tbl) # a full page, linking the assets instead of inlining them format(tbl, fragment = FALSE, inline_assets = FALSE)
Entry point of the lightweight grammar of tables. Returns an object (a
list) that records the data plus a list of table-modifying operations. The
object is rendered to HTML by format() (called automatically by the
print method).
lt(data, ...) ## Default S3 method: lt(data, auto_format = TRUE, auto_label = TRUE, show_types = FALSE, ...) ## S3 method for class 'ts' lt(data, wide = NCOL(data) == 1 && frequency(data) %in% c(4, 12), ...)lt(data, ...) ## Default S3 method: lt(data, auto_format = TRUE, auto_label = TRUE, show_types = FALSE, ...) ## S3 method for class 'ts' lt(data, wide = NCOL(data) == 1 && frequency(data) %in% c(4, 12), ...)
data |
A data frame (or anything coercible to one). |
... |
Arguments passed to methods. |
auto_format |
Whether to automatically format numeric columns (rounding,
thousand separators, percentage detection) and date/time columns (as
|
auto_label |
Whether to automatically clean column names for display
by replacing separators ( |
show_types |
Whether to tag each column with its type (e.g., |
wide |
For a time series (class |
A table object that can be piped into lt_*() functions.
By default all cell values and text (titles, labels, footnotes, ...) are
HTML-escaped, so special characters like <, >, and & render as
literal text. To emit content as raw HTML instead:
For body cells, mark whole columns with lt_html().
For a title, subtitle, column label, spanner, footnote, or note, wrap the
text in I(). For example, lt_header(x, I("<b>Report</b>")) renders the
title as raw HTML, while lt_header(x, "<b>Report</b>") shows the literal
<b> tags.
When a cell value has been formatted (e.g., by auto-formatting or
lt_format()), the original value is stored in the cell's title
attribute and shown as a tooltip on hover. Additionally:
Alt + Click on a table toggles display of all raw values in that table.
Alt + Double-Click on a table toggles raw values globally (all tables
on the page).
Raw values are shown as (value) after the formatted text, highlighted
with a light yellow background.
By default, missing (NA) cells display an em dash (—) so they are not
confused with empty strings. Change the table-wide default with the
lt.missing global option, e.g. options(lt.missing = "n/a"); set it to
the empty string (options(lt.missing = "")) to leave NA cells blank.
Use lt_sub() with missing = to override the text for specific columns.
litedown::fuse() documentsA document often shows several tables built from the same data, e.g., one
data frame with different columns, groups, or formatting in each table.
To keep the output file small, lt() writes the data into the document only
once; the other tables just point to that copy instead of repeating the
data. This happens automatically when the document is rendered by
litedown::fuse(), including documents that include child documents.
Sharing saves space except for tiny data: a data frame with roughly 15 cells
or fewer (e.g., 5 rows by 3 columns) is about as small as the pointer to it,
so sharing it gains nothing and may add a few bytes. For anything larger, the
saving grows with the size of the data and the number of tables using it.
To share only data frames above a certain size, set the lt.share_size
global option (in bytes, as reported by utils::object.size()), e.g.,
options(lt.share_size = 1e4); smaller data is then written into each
table. Use options(lt.share_size = Inf) to turn sharing off.
d = data.frame( total_sales = c(1234567.891, 98765.4321), growth_pct = c(0.1234, 0.0567), start = as.Date(c("2024-01-15", "2024-06-30")) ) # numbers, percentages, and column names are cleaned up for display lt(d) # raw column names and values lt(d, auto_label = FALSE, auto_format = FALSE) # a type tag under each column label lt(d, show_types = TRUE) # a monthly time series: one row per year, one column per month lt(AirPassengers) # a quarterly series, as a Time and value table; multiple series get a # column each q = ts(c(10.2, 11.5, 9.8, 12.1, 13.4, 12.9), start = c(2023, 1), frequency = 4) lt(q, wide = FALSE) lt(cbind(sales = q, cost = q * 0.6))d = data.frame( total_sales = c(1234567.891, 98765.4321), growth_pct = c(0.1234, 0.0567), start = as.Date(c("2024-01-15", "2024-06-30")) ) # numbers, percentages, and column names are cleaned up for display lt(d) # raw column names and values lt(d, auto_label = FALSE, auto_format = FALSE) # a type tag under each column label lt(d, show_types = TRUE) # a monthly time series: one row per year, one column per month lt(AirPassengers) # a quarterly series, as a Time and value table; multiple series get a # column each q = ts(c(10.2, 11.5, 9.8, 12.1, 13.4, 12.9), start = c(2023, 1), frequency = 4) lt(q, wide = FALSE) lt(cbind(sales = q, cost = q * 0.6))
Override the auto-detected alignment for specific columns. By default, numeric columns are right-aligned and character columns are left-aligned.
lt_align(x, columns, align = c("left", "center", "right"))lt_align(x, columns, align = c("left", "center", "right"))
x |
An |
columns |
Columns to select: a character vector of column names,
integer positions, or a one-sided formula. A formula whose right-hand side
references the pronoun |
align |
One of |
x with the alignment recorded.
d = airquality[1:3, 1:4] # numbers align right by default; select columns by name or by a predicate lt(d) |> lt_align(~ Wind, "center") |> lt_align(~ startsWith(., "S"), "left")d = airquality[1:3, 1:4] # numbers align right by default; select columns by name or by a predicate lt(d) |> lt_align(~ Wind, "center") |> lt_align(~ startsWith(., "S"), "left")
Fill the background of numeric cells with a color from a continuous scale,
like gt::data_color(). Each value is mapped to a position between the low
and high end of the domain, and its color is interpolated between the
palette colors. Cells that are not finite numbers (such as NA) are left
unfilled.
lt_color( x, columns, palette = c("white", "#fc8d59"), domain = NULL, contrast = TRUE )lt_color( x, columns, palette = c("white", "#fc8d59"), domain = NULL, contrast = TRUE )
x |
An |
columns |
Character names, integer positions, or a one-sided formula
(see |
palette |
Two or more colors (names or hex codes) spread evenly over the domain, from low to high. A single color is used as the high end, with white as the low end. |
domain |
A numeric vector |
contrast |
If |
x with the coloring recorded.
d = data.frame(a = c(-2, 0, 2), b = c(-1, 1, 3), c = c(10, 20, NA)) # one shared diverging scale for a and b; c has its own range (NA stays # unfilled), and a single color is the high end lt(d) |> lt_color(~ a + b, c("steelblue", "white", "tomato"), domain = c(-3, 3)) |> lt_color(~ c, "navy") # dark fills get white text automatically; contrast = FALSE turns that off lt(d) |> lt_color(~ a, c("white", "navy"), contrast = FALSE)d = data.frame(a = c(-2, 0, 2), b = c(-1, 1, 3), c = c(10, 20, NA)) # one shared diverging scale for a and b; c has its own range (NA stays # unfilled), and a single color is the high end lt(d) |> lt_color(~ a + b, c("steelblue", "white", "tomato"), domain = c(-3, 3)) |> lt_color(~ c, "navy") # dark fills get white text automatically; contrast = FALSE turns that off lt(d) |> lt_color(~ a, c("white", "navy"), contrast = FALSE)
Add user-supplied stylesheets or inline rules that render after the built-in CSS, so rules can override the defaults. Inline rules are scoped to the table; stylesheets are page-wide, as usual.
lt_css(x, ...)lt_css(x, ...)
x |
An |
... |
Unnamed arguments are stylesheet paths or URLs. A bare
filename (no directory component) that does not exist in the working
directory is resolved against the stylesheets shipped with lt, so
e.g. Named arguments define inline CSS rules that apply to this table only (other
tables on the page are unaffected). Names
are selectors (e.g., |
x with the stylesheets recorded.
d = trees[1:4, ] # rules for this table only: a selector and a CSS string or list lt(d) |> lt_style(~ Girth, test = "v => v > 8.5", class = "high") |> lt_css(.high = list(background = "#cfc", fontWeight = "bold"), td = "color: #06c") # a stylesheet (here one shipped with lt) lt(d) |> lt_css("lt-plot.css")d = trees[1:4, ] # rules for this table only: a selector and a CSS string or list lt(d) |> lt_style(~ Girth, test = "v => v > 8.5", class = "high") |> lt_css(.high = list(background = "#cfc", fontWeight = "bold"), td = "color: #06c") # a stylesheet (here one shipped with lt) lt(d) |> lt_css("lt-plot.css")
Format date or datetime columns using JavaScript's native Date methods.
The underlying data should be Date or POSIXt in R (serialized as
new Date(...) for the browser). Without this, such columns are shown as
YYYY-MM-DD (dates) or YYYY-MM-DD HH:MM:SS (date-times) when
auto_format = TRUE in lt().
lt_date(x, columns, method = NULL, locale = NULL, options = NULL)lt_date(x, columns, method = NULL, locale = NULL, options = NULL)
x |
An |
columns |
Columns to select: a character vector of column names,
integer positions, or a one-sided formula. A formula whose right-hand side
references the pronoun |
method |
A JS Date method name to call (e.g., |
locale |
A BCP 47 locale string (e.g., |
options |
A named list of
|
x with the date formatting recorded.
A date (without a time) is a calendar day and displays as the same day
in every time zone, so do not set timeZone for it: timeZone = "UTC"
would show 2024-01-14 for 2024-01-15 to a viewer east of Greenwich.
A date-time is an instant and displays in the viewer's local time zone by
default; set options = list(timeZone = "UTC") (or another zone) to show
the same clock time to everyone.
d = data.frame( event = c("Launch", "Update"), date = as.Date(c("2024-01-15", "2024-06-30")), time = as.POSIXct(c("2024-01-15 09:30:00", "2024-06-30 17:45:00"), tz = "UTC") ) # locale and Intl.DateTimeFormat options, or call a JavaScript Date method lt(d) |> lt_date(~ date, locale = "fr-FR", options = list( weekday = "long", day = "numeric", month = "long" )) |> lt_date(~ time, method = "toISOString")d = data.frame( event = c("Launch", "Update"), date = as.Date(c("2024-01-15", "2024-06-30")), time = as.POSIXct(c("2024-01-15 09:30:00", "2024-06-30 17:45:00"), tz = "UTC") ) # locale and Intl.DateTimeFormat options, or call a JavaScript Date method lt(d) |> lt_date(~ date, locale = "fr-FR", options = list( weekday = "long", day = "numeric", month = "long" )) |> lt_date(~ time, method = "toISOString")
The htmltools::htmlDependency() bundling lt's runtime assets, for embedding
lt tables in other HTML output (e.g. another htmlwidget or a reactable
cell) and rendering them client-side with LT.render() / LT.buildHtml()
on a spec from lt_spec(). Requires the htmltools package.
lt_dependency(interactive = FALSE, plot = FALSE, shiny = FALSE, input = FALSE)lt_dependency(interactive = FALSE, plot = FALSE, shiny = FALSE, input = FALSE)
interactive |
Whether to also include the interactivity extension (the
assets behind |
plot |
Whether to also include the graphics module (the assets behind
|
shiny |
Whether to include the Shiny output binding (only needed by
|
input |
Whether to include the editing extension and Shiny input
binding (only needed by |
An html_dependency object.
if (requireNamespace("htmltools", quietly = TRUE)) { # the core runtime only lt_dependency() # with interactivity and inline plots lt_dependency(interactive = TRUE, plot = TRUE) }if (requireNamespace("htmltools", quietly = TRUE)) { # the core runtime only lt_dependency() # with interactivity and inline plots lt_dependency(interactive = TRUE, plot = TRUE) }
Render each row's values across one or more columns as inline dots on a
shared horizontal scale: N columns give N dots per row, laid out by value. It
is lightweight like lt_errorbar() and lt_sparkline() – only the numbers
travel to the client and the SVG is drawn in the browser, so an interactive
table (lt_interactive()) draws only the rows on the current page.
lt_dotplot( x, columns, limits = NULL, color = FALSE, labels = NULL, stagger = FALSE, into = NULL, width = 160, height = NULL, hide = TRUE, axis = TRUE )lt_dotplot( x, columns, limits = NULL, color = FALSE, labels = NULL, stagger = FALSE, into = NULL, width = 160, height = NULL, hide = TRUE, axis = TRUE )
x |
An |
columns |
The value column(s): one dot is drawn per column, read left to
right across the row, all on a scale shared across the columns. The plot is
drawn in the first column's cells, or into |
limits |
Numeric |
color |
Series colors. |
labels |
Legend labels, one per series, used when colored. Defaults to the series' value-column names. |
stagger |
If |
into |
Optional name of a dedicated column to draw the plot into,
instead of the first series' value column. The series columns ( |
width, height
|
Pixel size of each cell's SVG. |
hide |
If |
axis |
Draw a shared horizontal axis (a baseline with tick marks and
labels at "nice" round values) in the table footer under the plot column,
plus faint vertical gridlines inside each cell at the same tick positions
to help read the bars. |
Since the cell shows every named column, the column header defaults to all
their names joined by " / " (e.g. "Before / After"); override it with a
later lt_label() on that column.
x with the dot-plot column recorded.
d = data.frame( group = c("A", "B", "C"), before = c(3, 5, 4), after = c(6, 7, 4.1) ) # one dot per column, colored with a legend, a captioned axis, and separate # tracks so near-equal values (group C) do not overlap lt(d) |> lt_dotplot(~ before + after, color = TRUE, axis = "Score", stagger = TRUE) # custom colors and labels, a fixed scale with no axis, a custom size lt(d) |> lt_dotplot( ~ before + after, color = c("#999", "#1a9641"), labels = c("Baseline", "Follow-up"), limits = c(0, 10), axis = FALSE, width = 200, height = 20 ) # a dedicated column, keeping the value columns visible as text lt(d) |> lt_dotplot(~ before + after, into = "plot", hide = FALSE)d = data.frame( group = c("A", "B", "C"), before = c(3, 5, 4), after = c(6, 7, 4.1) ) # one dot per column, colored with a legend, a captioned axis, and separate # tracks so near-equal values (group C) do not overlap lt(d) |> lt_dotplot(~ before + after, color = TRUE, axis = "Score", stagger = TRUE) # custom colors and labels, a fixed scale with no axis, a custom size lt(d) |> lt_dotplot( ~ before + after, color = c("#999", "#1a9641"), labels = c("Baseline", "Follow-up"), limits = c(0, 10), axis = FALSE, width = 200, height = 20 ) # a dedicated column, keeping the value columns visible as text lt(d) |> lt_dotplot(~ before + after, into = "plot", hide = FALSE)
Render a numeric column's cells as a small inline SVG: a point at the
estimate and a horizontal bar (with end caps) from the lower to the upper
bound, drawn on a scale shared across the column so rows are comparable at a
glance (handy for
a forest plot of effect sizes with confidence intervals). It is lightweight:
only the numbers travel to the client, and the SVG is drawn in the browser —
so for an interactive table (lt_interactive()) only the rows on the current
page are drawn.
lt_errorbar( x, ..., limits = NULL, ref = NULL, into = NULL, width = 160, height = NULL, hide = TRUE, axis = FALSE, color = FALSE, labels = NULL )lt_errorbar( x, ..., limits = NULL, ref = NULL, into = NULL, width = 160, height = NULL, hide = TRUE, axis = FALSE, color = FALSE, labels = NULL )
x |
An |
... |
One or more error-bar series, each naming the point estimate, the
lower bound, and the upper bound, in that order: either a two-sided formula
|
limits |
Numeric |
ref |
Optional value at which to draw a vertical reference line (e.g.
|
into |
Optional name of a dedicated column to draw the plot into,
instead of the first series' value column. The series columns ( |
width, height
|
Pixel size of each cell's SVG. |
hide |
If |
axis |
Draw a shared horizontal axis (a baseline with tick marks and
labels at "nice" round values) in the table footer under the plot column,
plus faint vertical gridlines inside each cell at the same tick positions
to help read the bars. |
color |
Series colors. |
labels |
Legend labels, one per series, used when colored. Defaults to the series' value-column names. |
Several series can share one cell: pass one triple per series and each row
shows one point-and-bar per series, stacked vertically on the same shared
scale (e.g. a risk difference for each of several treatment arms). Color the
series and a legend is drawn in the footer, as for lt_dotplot().
x with the error-bar column recorded.
d = data.frame( term = c("A", "B", "C"), est = c(0.2, -0.1, 0.4), lo = c(0.0, -0.3, 0.1), hi = c(0.4, 0.1, 0.7) ) # estimate (LHS) and bounds (RHS) draw into the estimate column, with a # reference line, a captioned axis, a fixed scale, and a taller plot lt(d) |> lt_errorbar( est ~ lo + hi, ref = 0, axis = "Effect", limits = c(-0.5, 1), height = 24 ) # a dedicated column, keeping the value columns visible as text lt(d) |> lt_errorbar(est ~ lo + hi, into = "forest", hide = FALSE) # fit the plot to its column (resizes with it) lt(d) |> lt_errorbar(est ~ lo + hi, into = "forest", width = "100%") # several series per cell, colored, with a legend d2 = data.frame( term = c("A", "B"), e1 = c(0.2, 0.4), l1 = c(0, 0.2), u1 = c(0.4, 0.6), e2 = c(-0.1, 0.1), l2 = c(-0.3, -0.1), u2 = c(0.1, 0.3) ) lt(d2) |> lt_errorbar( e1 ~ l1 + u1, e2 ~ l2 + u2, ref = 0, color = TRUE, labels = c("Drug A", "Drug B") ) # explicit colors lt(d2) |> lt_errorbar( e1 ~ l1 + u1, e2 ~ l2 + u2, color = c("#d7191c", "#2c7bb6") )d = data.frame( term = c("A", "B", "C"), est = c(0.2, -0.1, 0.4), lo = c(0.0, -0.3, 0.1), hi = c(0.4, 0.1, 0.7) ) # estimate (LHS) and bounds (RHS) draw into the estimate column, with a # reference line, a captioned axis, a fixed scale, and a taller plot lt(d) |> lt_errorbar( est ~ lo + hi, ref = 0, axis = "Effect", limits = c(-0.5, 1), height = 24 ) # a dedicated column, keeping the value columns visible as text lt(d) |> lt_errorbar(est ~ lo + hi, into = "forest", hide = FALSE) # fit the plot to its column (resizes with it) lt(d) |> lt_errorbar(est ~ lo + hi, into = "forest", width = "100%") # several series per cell, colored, with a legend d2 = data.frame( term = c("A", "B"), e1 = c(0.2, 0.4), l1 = c(0, 0.2), u1 = c(0.4, 0.6), e2 = c(-0.1, 0.1), l2 = c(-0.3, -0.1), u2 = c(0.1, 0.3) ) lt(d2) |> lt_errorbar( e1 ~ l1 + u1, e2 ~ l2 + u2, ref = 0, color = TRUE, labels = c("Drug A", "Drug B") ) # explicit colors lt(d2) |> lt_errorbar( e1 ~ l1 + u1, e2 ~ l2 + u2, color = c("#d7191c", "#2c7bb6") )
Save a table to disk. The output format is chosen from the file extension
of output: .html writes an HTML table, .pdf writes a vector PDF, .csv
and .rtf write the table's text (all rows, with the title, column spanners,
and notes in RTF; this needs Node.js or a Chromium-based browser), and any
other extension writes a PNG. PDF and PNG are produced by rendering the table in a headless Chromium
browser (via xfun::browser_print()).
lt_export( x, output = "lt.html", method = c("auto", "node", "browser", "raw"), css = TRUE, fragment = FALSE, tidy = FALSE, crop = TRUE, width = NULL, padding = 8, browser = NULL, ... )lt_export( x, output = "lt.html", method = c("auto", "node", "browser", "raw"), css = TRUE, fragment = FALSE, tidy = FALSE, crop = TRUE, width = NULL, padding = 8, browser = NULL, ... )
x |
An |
output |
Output file path. Its extension selects the format: |
method |
How to produce the HTML |
css |
Whether to include the lt.css runtime stylesheet in the HTML
output. User CSS from |
fragment |
If |
tidy |
Whether to pretty-print the baked |
crop |
Whether to crop the PDF/PNG tightly to the table, removing the
surrounding page whitespace. This adds a preliminary browser pass to
measure the rendered table. Set to |
width |
The width of the table: a number of CSS pixels, or a CSS width
string such as |
padding |
Padding in CSS pixels to keep around the table when
cropping. A single value (all sides) or a length-two vector
|
browser |
Path to the Chromium-based browser; passed to
|
... |
Passed to |
For .html output, method controls how the <table> is produced:
"raw" writes the JavaScript-spec HTML, so the table is built in the
browser by the lt.js runtime when the file is viewed; the other methods
bake a static <table> up front by running lt.js once (via "node" in
Node.js or "browser" in a headless Chromium browser; "auto" picks Node
if available, else the browser), so the saved file needs no JavaScript to
view. method, css, fragment, and tidy apply only to .html output.
The output path, or (when output is NA) the HTML as a string.
When the option lt.lt_static is set to a list of arguments (e.g.,
options(lt.lt_static = list(css = FALSE))), the
knit_print and record_print
methods emit the same static HTML table as lt_export(x, "*.html") (using
those arguments as method/css/fragment) instead of the default
JavaScript-based spec. This is useful for output formats that support raw
HTML but cannot run JavaScript (e.g., GitHub Flavored Markdown).
tbl = lt(ToothGrowth[1:3, ]) |> lt_header("Guinea pigs") # HTML with the JavaScript spec (table built by lt.js when viewed) f1 = tempfile(fileext = ".html") lt_export(tbl, f1, method = "raw") # a static <table> (needs Node.js or a headless browser), returned as a # string: just the fragment, without the lt.css stylesheet, pretty-printed if (lt:::can_bake()) lt_export(tbl, NA, fragment = TRUE, css = FALSE, tidy = TRUE) # PDF and PNG are rendered in a headless browser and cropped to the table f2 = tempfile(fileext = ".pdf") f3 = tempfile(fileext = ".png") if (lt:::has_browser(pdf = TRUE)) { lt_export(tbl, f2) # the table's width in pixels, more padding, no cropping lt_export(tbl, f3, width = 400, padding = c(16, 24)) lt_export(tbl, f3, crop = FALSE) } # the table's text as CSV or RTF f4 = tempfile(fileext = ".rtf") if (lt:::has_node()) lt_export(tbl, f4) unlink(c(f1, f2, f3, f4))tbl = lt(ToothGrowth[1:3, ]) |> lt_header("Guinea pigs") # HTML with the JavaScript spec (table built by lt.js when viewed) f1 = tempfile(fileext = ".html") lt_export(tbl, f1, method = "raw") # a static <table> (needs Node.js or a headless browser), returned as a # string: just the fragment, without the lt.css stylesheet, pretty-printed if (lt:::can_bake()) lt_export(tbl, NA, fragment = TRUE, css = FALSE, tidy = TRUE) # PDF and PNG are rendered in a headless browser and cropped to the table f2 = tempfile(fileext = ".pdf") f3 = tempfile(fileext = ".png") if (lt:::has_browser(pdf = TRUE)) { lt_export(tbl, f2) # the table's width in pixels, more padding, no cropping lt_export(tbl, f3, width = 400, padding = c(16, 24)) lt_export(tbl, f3, crop = FALSE) } # the table's text as CSV or RTF f4 = tempfile(fileext = ".rtf") if (lt:::has_node()) lt_export(tbl, f4) unlink(c(f1, f2, f3, f4))
Attaches a footnote text to a table region. Footnotes are numbered
automatically in the order they are added (de-duplicated by text).
lt_footnote(x, text, where, columns = NULL, rows = NULL, match = NULL)lt_footnote(x, text, where, columns = NULL, rows = NULL, match = NULL)
x |
An |
text |
Footnote text. |
where |
One of |
columns |
Character names, integer positions, or a one-sided formula
(for |
rows |
Integer vector of 1-based row indices (for |
match |
For |
x with the footnote recorded.
d = data.frame( Arm = c("Treatment", "Treatment", "Control", "Control"), Stat = c("n", "Mean", "n", "Mean"), Value = c(31, 6.8, 30, 4.2), SE = c(NA, 0.42, NA, 0.38) ) tbl = lt(d) |> lt_group(~ Arm) |> lt_header("Study Results", "Two arms") |> lt_spanner(Summary ~ Value + SE) # one footnote for each of the six locations tbl |> lt_footnote("Source: simulated trial data.", "title") |> lt_footnote("Intention-to-treat population.", "subtitle") |> lt_footnote("Standard error of the mean.", "column", ~ SE) |> lt_footnote("Per-arm summary statistics.", "spanner", ~ Summary) |> lt_footnote("Received active drug.", "group", ~ Treatment) |> lt_footnote("SE is undefined for counts.", "body", ~ SE, rows = c(1, 3)) # match groups by prefix, or all of them; raw HTML text (wrap in I()) tbl |> lt_footnote("Starts with T.", "group", "T", match = "starts_with") |> lt_footnote(I("See <a href='#'>docs</a>."), "group", match = "all")d = data.frame( Arm = c("Treatment", "Treatment", "Control", "Control"), Stat = c("n", "Mean", "n", "Mean"), Value = c(31, 6.8, 30, 4.2), SE = c(NA, 0.42, NA, 0.38) ) tbl = lt(d) |> lt_group(~ Arm) |> lt_header("Study Results", "Two arms") |> lt_spanner(Summary ~ Value + SE) # one footnote for each of the six locations tbl |> lt_footnote("Source: simulated trial data.", "title") |> lt_footnote("Intention-to-treat population.", "subtitle") |> lt_footnote("Standard error of the mean.", "column", ~ SE) |> lt_footnote("Per-arm summary statistics.", "spanner", ~ Summary) |> lt_footnote("Received active drug.", "group", ~ Treatment) |> lt_footnote("SE is undefined for counts.", "body", ~ SE, rows = c(1, 3)) # match groups by prefix, or all of them; raw HTML text (wrap in I()) tbl |> lt_footnote("Starts with T.", "group", "T", match = "starts_with") |> lt_footnote(I("See <a href='#'>docs</a>."), "group", match = "all")
Control the number of decimal places and thousands separator for numeric
columns. Columns passed to this function are excluded from automatic
formatting (see the auto_format argument of lt()). To disable auto-format
for a column without otherwise changing its display, call lt_format(x, ~col) with no other arguments.
lt_format( x, columns, decimals = NULL, sig_digits = NULL, big_mark = NULL, percent = NULL, prefix = NULL, suffix = NULL )lt_format( x, columns, decimals = NULL, sig_digits = NULL, big_mark = NULL, percent = NULL, prefix = NULL, suffix = NULL )
x |
An |
columns |
Columns to select: a character vector of column names,
integer positions, or a one-sided formula. A formula whose right-hand side
references the pronoun |
decimals |
Number of decimal places (default |
sig_digits |
Number of significant digits (e.g., |
big_mark |
Thousands separator (e.g., |
percent |
If |
prefix |
String prepended to each formatted value (e.g., |
suffix |
String appended to each formatted value (e.g., |
x with the formatting recorded.
d = data.frame( item = c("A", "B", "C"), price = c(1234567.891, 98765.432, 4321.0987), share = c(0.1234, 0.0567, 0.8199), rate = c(12.34, 5.67, 81.99), mass = c(123456.7, 98765.43, 1234.567), weight = c(1250, 340.5, 89.12) ) lt(d) |> # decimals, a thousands mark, and a prefix lt_format(~ price, decimals = 2, big_mark = ",", prefix = "$") |> # percent: values are multiplied by 100; "%" only appends the sign lt_format(~ share, decimals = 1, percent = TRUE) |> lt_format(~ rate, decimals = 1, percent = "%") |> # significant digits: 123456.7 becomes 123000 lt_format(~ mass, sig_digits = 3) |> lt_format(~ weight, decimals = 1, suffix = " kg")d = data.frame( item = c("A", "B", "C"), price = c(1234567.891, 98765.432, 4321.0987), share = c(0.1234, 0.0567, 0.8199), rate = c(12.34, 5.67, 81.99), mass = c(123456.7, 98765.43, 1234.567), weight = c(1250, 340.5, 89.12) ) lt(d) |> # decimals, a thousands mark, and a prefix lt_format(~ price, decimals = 2, big_mark = ",", prefix = "$") |> # percent: values are multiplied by 100; "%" only appends the sign lt_format(~ share, decimals = 1, percent = TRUE) |> lt_format(~ rate, decimals = 1, percent = "%") |> # significant digits: 123456.7 becomes 123000 lt_format(~ mass, sig_digits = 3) |> lt_format(~ weight, decimals = 1, suffix = " kg")
Partition rows into labeled groups. Pass column names to group by those
columns' values (the columns are removed from the body and rendered as
rowspan cells on the left). Use sep = TRUE to render groups as
full-width separator rows instead of rowspan.
lt_group(x, ..., sep = "auto", sort = TRUE)lt_group(x, ..., sep = "auto", sort = TRUE)
x |
An |
... |
A column name, integer position, or formula (e.g., |
sep |
If |
sort |
If |
x with the row groups recorded.
d = data.frame( arm = c("Placebo", "Placebo", "Treatment", "Treatment"), stat = c("n", "Mean", "n", "Mean"), value = c(30, 4.2, 31, 6.8) ) # group by a column: spanning cells on the left lt(d) |> lt_group(~ arm) # full-width separator rows instead lt(d) |> lt_group(~ arm, sep = TRUE) # keep the original row order rather than sorting by group lt(d[c(3, 1, 4, 2), ]) |> lt_group(~ arm, sort = FALSE) # manual groups: name the rows (always separator rows) tbl = lt(ToothGrowth[1:6, ]) tbl |> lt_group("First three" = 1:3, "Last three" = 4:6) # ... or give a condition on the data tbl |> lt_group(Short = ~ len <= 8, Long = ~ len > 8) # unnamed labels reorder the groups lt(d) |> lt_group(~ arm, sep = TRUE) |> lt_group("Treatment", "Placebo")d = data.frame( arm = c("Placebo", "Placebo", "Treatment", "Treatment"), stat = c("n", "Mean", "n", "Mean"), value = c(30, 4.2, 31, 6.8) ) # group by a column: spanning cells on the left lt(d) |> lt_group(~ arm) # full-width separator rows instead lt(d) |> lt_group(~ arm, sep = TRUE) # keep the original row order rather than sorting by group lt(d[c(3, 1, 4, 2), ]) |> lt_group(~ arm, sort = FALSE) # manual groups: name the rows (always separator rows) tbl = lt(ToothGrowth[1:6, ]) tbl |> lt_group("First three" = 1:3, "Last three" = 4:6) # ... or give a condition on the data tbl |> lt_group(Short = ~ len <= 8, Long = ~ len > 8) # unnamed labels reorder the groups lt(d) |> lt_group(~ arm, sep = TRUE) |> lt_group("Treatment", "Placebo")
Add a title and subtitle
lt_header(x, title = NULL, subtitle = NULL)lt_header(x, title = NULL, subtitle = NULL)
x |
An |
title |
A character scalar. Wrap in |
subtitle |
A character scalar. Wrap in |
x with the header recorded.
d = ToothGrowth[1:3, ] lt(d) |> lt_header("Tooth Growth in Guinea Pigs", "First 3 rows") # a title only; raw HTML (wrap in I()) lt(d) |> lt_header(I("<em>Tooth</em> Growth"))d = ToothGrowth[1:3, ] lt(d) |> lt_header("Tooth Growth in Guinea Pigs", "First 3 rows") # a title only; raw HTML (wrap in I()) lt(d) |> lt_header(I("<em>Tooth</em> Growth"))
Drop columns from the rendered table without removing them from the data.
The values still travel to the client in the spec, so they remain available
to things that read the whole row, such as an interactive table's row detail
(see the detail argument of lt_interactive()).
lt_hide(x, columns)lt_hide(x, columns)
x |
An |
columns |
Columns to select: a character vector of column names,
integer positions, or a one-sided formula. A formula whose right-hand side
references the pronoun |
x with the hidden columns recorded.
tbl = lt(esoph[1:3, ]) |> lt_hide(~ ncases + ncontrols) tbl # the hidden data still reaches the row detail tbl |> lt_interactive(detail = ~ ncases + ncontrols)tbl = lt(esoph[1:3, ]) |> lt_hide(~ ncases + ncontrols) tbl # the hidden data still reaches the row detail tbl |> lt_interactive(detail = ~ ncases + ncontrols)
Mark whole columns so their body cells are emitted as raw HTML instead of
being escaped. By default every cell is HTML-escaped (so <, >, and &
render as literal text); use this to embed links, emphasis, or other markup
in a column's cells.
lt_html(x, columns)lt_html(x, columns)
x |
An |
columns |
Columns whose cells are raw HTML: character names, integer
positions, or a one-sided formula (predicate formulas such as
|
To emit raw HTML in other regions (title, column labels, footnotes, ...),
wrap the text in I() in the corresponding lt_*() function instead.
x with the raw-HTML columns recorded.
d = data.frame( name = c("<a href='#a'>A</a>", "<a href='#b'>B</a>"), note = c("<b>bold</b>", "<i>italic</i>") ) # escaped by default lt(d) # one column as raw HTML lt(d) |> lt_html(~ name) # all columns as raw HTML lt(d) |> lt_html()d = data.frame( name = c("<a href='#a'>A</a>", "<a href='#b'>B</a>"), note = c("<b>bold</b>", "<i>italic</i>") ) # escaped by default lt(d) # one column as raw HTML lt(d) |> lt_html(~ name) # all columns as raw HTML lt(d) |> lt_html()
Add hierarchical indentation to the first column of specified rows.
lt_indent(x, rows, level = 1)lt_indent(x, rows, level = 1)
x |
An |
rows |
Integer vector of 1-based row indices to indent. |
level |
Indent level (default 1). Each level adds one unit of left padding. |
x with the indentation recorded.
d = data.frame( label = c("Any AE", "Cardiac", "Tachycardia", "GI", "Nausea"), n = c(45, 30, 15, 20, 12) ) # one level lt(d) |> lt_indent(c(2, 4)) # nested: rows by position, each with its level lt(d) |> lt_indent(c(2, 4), level = 1) |> lt_indent(c(3, 5), level = 2)d = data.frame( label = c("Any AE", "Cardiac", "Tachycardia", "GI", "Nausea"), n = c(45, 30, 15, 20, 12) ) # one level lt(d) |> lt_indent(c(2, 4)) # nested: rows by position, each with its level lt(d) |> lt_indent(c(2, 4), level = 1) |> lt_indent(c(3, 5), level = 2)
Make a table interactive in the browser: pagination, a table-wide search box, click-to-sort column headers, per-column filter boxes, and resizable columns. The features are handled client-side by an opt-in JavaScript extension, loaded only for tables that call this function.
lt_interactive( x, sort = TRUE, search = TRUE, filter = "auto", pager = c(10, 25, 50, Inf), resize = TRUE, hide = NULL, detail = NULL, profile = FALSE, download = FALSE )lt_interactive( x, sort = TRUE, search = TRUE, filter = "auto", pager = c(10, 25, 50, Inf), resize = TRUE, hide = NULL, detail = NULL, profile = FALSE, download = FALSE )
x |
An |
sort |
Whether clicking a column header sorts the table by that column
(cycling ascending, descending, then unsorted); shift-clicking adds a
column as a further tie-breaker, so several columns can sort at once.
Sorting uses the raw values, so numeric columns sort numerically and dates
and date-times chronologically. Can also request an initial sort by one or
more columns, given either as a character vector of column names or as a
one-sided formula (e.g. |
search |
Whether to show a table-wide search box. A row is kept when
any cell matches the term. Besides plain substring matching, a term that
references the cell variable |
filter |
The per-column filters. |
pager |
The page sizes to offer, as a vector of row counts; the
first one is used initially. Paging shows that many of the filtered and
sorted rows at a time, with a pager (first, previous, next, last), the row
range, and (for more than one size) a selector below the table. |
resize |
Whether to let the reader drag a column's right edge to resize
it (double-clicking the edge fits the column to its content). Widening a
column widens the table, leaving the other columns as they are. Initial
widths can be set with |
hide |
Column-visibility control: an eye button in the
control bar opens a checklist of every column, where unchecking a column
hides it (header and cells) and re-checking restores it. |
detail |
Row detail (drill-down). An expand caret is added to each row;
clicking it reveals a table built from that row below it. Give the columns
to show, as a character vector of names or a one-sided formula (e.g.
|
profile |
Whether to show a profile of each column: a mini bar chart of
its values (a histogram of up to 10 bins for numbers, dates, and
date-times; one bar per category for text, left blank if over half of
the values are distinct). Hovering over it shows summary statistics (min,
max, and mean, or the number of distinct values and the most frequent ones)
and the amount of missing values. When the filters keep only some rows, the bars
highlight their share. |
download |
Whether to add a button that downloads the table. The file
holds the current view (every row the filters and search keep, in sort
order, across all pages) of the table's columns, with the title, column
spanners, and notes of formats that have room for them. The button opens a
menu of the available formats (CSV and RTF); with a single format, it
downloads directly. |
Sorting and filtering respect the row structure, happening within each
group or subtree rather than across it. Separator row groups (lt_group()
with sep = TRUE, or manual groups) keep their order, and a group whose rows
all filter out drops its header. Indentation (lt_indent()) sorts siblings
under each parent, and an indented child keeps its ancestors visible for
context. Rowspan row groups (lt_group() with its default rowspan rendering)
sort and filter within each run and clicking a group header reorders its
blocks; with several group columns the view stays nested (an inner column
reorders only within its parent block), and the spanning cells are redrawn to
match.
x with interactivity enabled.
# click-to-sort headers, a search box, column filters, and paging; "auto" # gives Type a checklist (text with few values) and numbers a range slider lt(CO2) |> lt_interactive() # an initial sort (Diet, then weight descending), page sizes (the first is # used initially; Inf shows all rows), a widget per filter (FALSE for none), # and fixed (non-resizable) columns lt(ChickWeight) |> lt_interactive( sort = ~ Diet + -weight, pager = c(5, 10, Inf), resize = FALSE, filter = list("auto", weight = "range", Diet = "select", Time = FALSE) ) # keep only the search box, no individual column filters, no pager lt(head(airquality)) |> lt_interactive(sort = FALSE, filter = FALSE, pager = FALSE) # filter boxes for specific columns only lt(warpbreaks) |> lt_interactive(filter = c('wool', 'breaks')) # a column-visibility menu with a label and some columns hidden to start # (hide = NA shows all columns; a bare formula hides those columns) lt(esoph) |> lt_interactive(hide = NA) lt(esoph) |> lt_interactive(hide = list(label = 'Show columns', columns = ~ ncontrols)) # row detail: hidden columns revealed when a row is expanded lt(esoph) |> lt_hide(~ ncases + ncontrols) |> lt_interactive(detail = ~ ncases + ncontrols) # a JavaScript callback: (raw row, index, displayed row) to a table spec lt(chickwts) |> lt_interactive( detail = js('(row, i, d) => ({ data: { metric: ["row", "feed"], value: [i, d.feed] } })') ) # a distribution plot in each column header, or in the filter popover lt(airquality) |> lt_interactive(profile = TRUE) lt(ToothGrowth) |> lt_interactive(profile = 'filter') # a button to download the current view (CSV and RTF; a string sets the file # name), the raw unformatted values, or only RTF lt(PlantGrowth) |> lt_interactive(download = TRUE) lt(PlantGrowth) |> lt_interactive(download = list(file = 'plants.csv', mode = 'raw')) lt(PlantGrowth) |> lt_interactive(download = list(formats = 'rtf'))# click-to-sort headers, a search box, column filters, and paging; "auto" # gives Type a checklist (text with few values) and numbers a range slider lt(CO2) |> lt_interactive() # an initial sort (Diet, then weight descending), page sizes (the first is # used initially; Inf shows all rows), a widget per filter (FALSE for none), # and fixed (non-resizable) columns lt(ChickWeight) |> lt_interactive( sort = ~ Diet + -weight, pager = c(5, 10, Inf), resize = FALSE, filter = list("auto", weight = "range", Diet = "select", Time = FALSE) ) # keep only the search box, no individual column filters, no pager lt(head(airquality)) |> lt_interactive(sort = FALSE, filter = FALSE, pager = FALSE) # filter boxes for specific columns only lt(warpbreaks) |> lt_interactive(filter = c('wool', 'breaks')) # a column-visibility menu with a label and some columns hidden to start # (hide = NA shows all columns; a bare formula hides those columns) lt(esoph) |> lt_interactive(hide = NA) lt(esoph) |> lt_interactive(hide = list(label = 'Show columns', columns = ~ ncontrols)) # row detail: hidden columns revealed when a row is expanded lt(esoph) |> lt_hide(~ ncases + ncontrols) |> lt_interactive(detail = ~ ncases + ncontrols) # a JavaScript callback: (raw row, index, displayed row) to a table spec lt(chickwts) |> lt_interactive( detail = js('(row, i, d) => ({ data: { metric: ["row", "feed"], value: [i, d.feed] } })') ) # a distribution plot in each column header, or in the filter popover lt(airquality) |> lt_interactive(profile = TRUE) lt(ToothGrowth) |> lt_interactive(profile = 'filter') # a button to download the current view (CSV and RTF; a string sets the file # name), the raw unformatted values, or only RTF lt(PlantGrowth) |> lt_interactive(download = TRUE) lt(PlantGrowth) |> lt_interactive(download = list(file = 'plants.csv', mode = 'raw')) lt(PlantGrowth) |> lt_interactive(download = list(formats = 'rtf'))
Override column headers without modifying the underlying data frame.
lt_label(x, ...)lt_label(x, ...)
x |
An |
... |
Named arguments of the form |
x with the column label overrides recorded.
d = ToothGrowth[1:3, ] lt(d) |> lt_label(len = "length (mm)", dose = "dose (mg/day)") # raw HTML (wrap in I()) lt(d) |> lt_label(len = I("length<sup>*</sup>")) # a named vector or list, handy when labels are computed lt(d) |> lt_label(c(len = "length (mm)", dose = "dose (mg/day)")) # a list of two parallel vectors: names and labels lt(d) |> lt_label(list(c("len", "dose"), c("length (mm)", "dose (mg/day)")))d = ToothGrowth[1:3, ] lt(d) |> lt_label(len = "length (mm)", dose = "dose (mg/day)") # raw HTML (wrap in I()) lt(d) |> lt_label(len = I("length<sup>*</sup>")) # a named vector or list, handy when labels are computed lt(d) |> lt_label(c(len = "length (mm)", dose = "dose (mg/day)")) # a list of two parallel vectors: names and labels lt(d) |> lt_label(list(c("len", "dose"), c("length (mm)", "dose (mg/day)")))
Combine values from multiple columns into a single display column using a pattern. Source columns (all except the first) are hidden by default.
lt_merge(x, columns, pattern = NULL, hide = TRUE)lt_merge(x, columns, pattern = NULL, hide = TRUE)
x |
An |
columns |
Character names, integer positions, or a one-sided formula
(predicate formulas such as |
pattern |
A glue-style template using |
hide |
If |
x with the merge recorded.
d = data.frame( stat = c("Mean", "SD", "Median"), value = c(4.2, 1.1, 3.9), lo = c(2.0, 0.5, NA), hi = c(6.4, 1.7, NA) ) # drop the parenthesized part when a value is missing; the source columns # (all but the first) are hidden lt(d) |> lt_merge(~ value + lo + hi, pattern = "{1}<< ({2}, {3})>>") # keep the source columns visible lt(d) |> lt_merge(~ value + lo, hide = FALSE)d = data.frame( stat = c("Mean", "SD", "Median"), value = c(4.2, 1.1, 3.9), lo = c(2.0, 0.5, NA), hi = c(6.4, 1.7, NA) ) # drop the parenthesized part when a value is missing; the source columns # (all but the first) are hidden lt(d) |> lt_merge(~ value + lo + hi, pattern = "{1}<< ({2}, {3})>>") # keep the source columns visible lt(d) |> lt_merge(~ value + lo, hide = FALSE)
Rearrange column display order without modifying the data frame.
lt_move(x, columns, after = NULL)lt_move(x, columns, after = NULL)
x |
An |
columns |
Columns to select: a character vector of column names,
integer positions, or a one-sided formula. A formula whose right-hand side
references the pronoun |
after |
Column name or integer position after which to place the
moved columns. Use |
x with the column move recorded.
tbl = lt(airquality[1:3, ]) # after a column (by name or position) tbl |> lt_move(~ Month + Day, after = "Ozone") # to the front tbl |> lt_move(~ Temp, after = NULL)tbl = lt(airquality[1:3, ]) # after a column (by name or position) tbl |> lt_move(~ Month + Day, after = "Ozone") # to the front tbl |> lt_move(~ Temp, after = NULL)
Notes are rendered in the table footer below numbered footnotes.
lt_note(x, text)lt_note(x, text)
x |
An |
text |
Note text. Wrap in |
x with the note recorded.
d = women[1:3, ] # several notes; raw HTML (wrap in I()) lt(d) |> lt_note("Average heights and weights of American women aged 30-39.") |> lt_note(I("<b>height</b>: inches; <b>weight</b>: pounds."))d = women[1:3, ] # several notes; raw HTML (wrap in I()) lt(d) |> lt_note("Average heights and weights of American women aged 30-39.") |> lt_note(I("<b>height</b>: inches; <b>weight</b>: pounds."))
Use lt tables in Shiny apps, as outputs or as inputs.
lt_output(outputId, ...) render_lt(expr, env = parent.frame(), quoted = FALSE) lt_input(inputId, x, label = NULL, columns = NULL) lt_update(session, inputId, x, columns = NULL)lt_output(outputId, ...) render_lt(expr, env = parent.frame(), quoted = FALSE) lt_input(inputId, x, label = NULL, columns = NULL) lt_update(session, inputId, x, columns = NULL)
outputId |
Output variable name to read the table from. |
... |
Reserved for future use. |
expr |
An expression that returns an |
env |
Environment in which to evaluate |
quoted |
Whether |
inputId |
The input slot that will be used to access the value. |
x |
An |
label |
Display label for the input, or |
columns |
Names of the editable columns; all columns by default. For
|
session |
The |
lt_output() creates a UI placeholder; render_lt() supplies the table
spec from the server. Together they render an lt() table as a custom
Shiny output.
lt_input() shows a table whose body cells can be edited in the browser;
the edited table is available to the server as a data frame in
input[[inputId]]. lt_update() replaces the table from the server (e.g.,
to add or remove rows, or to reset the edits). Numeric columns accept only
numbers (an empty cell is NA); other columns hold text. Press Enter to
commit a cell and move down a row. Editing does not work with row groups
shown as spanning cells, nor with lt_interactive(), which reorders rows.
lt_output() and lt_input() return a Shiny UI element;
render_lt() returns a render function; lt_update() is called for its
side effect.
if (interactive()) { library(shiny) d = ToothGrowth[1:6, ] ui = fluidPage( lt_output("tbl"), # an editable table; only some columns can be edited lt_input("m", d, "Edit the cells:", columns = ~ len + dose), actionButton("reset", "Reset"), verbatimTextOutput("out") ) server = function(input, output, session) { output$tbl = render_lt(lt(d) |> lt_header("Tooth Growth")) output$out = renderPrint(input$m) # the edited data frame observeEvent(input$reset, lt_update(session, "m", d)) } shinyApp(ui, server) }if (interactive()) { library(shiny) d = ToothGrowth[1:6, ] ui = fluidPage( lt_output("tbl"), # an editable table; only some columns can be edited lt_input("m", d, "Edit the cells:", columns = ~ len + dose), actionButton("reset", "Reset"), verbatimTextOutput("out") ) server = function(input, output, session) { output$tbl = render_lt(lt(d) |> lt_header("Tooth Growth")) output$out = renderPrint(input$m) # the edited data frame observeEvent(input$reset, lt_update(session, "m", d)) } shinyApp(ui, server) }
Make an interactive table fetch its rows from a URL instead of holding them
in the page, for data too big for the browser: whenever the sort, filters,
search, or page change, the browser asks the server for just the current
page. By default the rows of x are served by a local app built on
xfun::new_app() (until xfun::stop_app()); pass url to use your own
server instead. Row groups, indentation, and row-specific styles and
footnotes are not supported. In a Shiny app, return the table from
render_lt() and the rows are served by the session itself (no local app is
started). See the examples in the package site for
details and the request/response format a custom server implements.
lt_serve( x, url = NULL, times = NULL, cols = NULL, n = NULL, name = "lt-server", ... )lt_serve( x, url = NULL, times = NULL, cols = NULL, n = NULL, name = "lt-server", ... )
x |
An |
url |
The URL of a data server (absolute, or relative to the page). By
default, a local app serving the rows of |
times, cols, n
|
For a custom |
name, ...
|
For the local app: its name and other arguments passed to
|
x, with the data URL added.
# rows stay in R; the browser fetches one page at a time (needs a live session) if (interactive()) { big = data.frame(id = 1:1e6, x = rnorm(1e6), g = sample(letters, 1e6, TRUE)) lt_viewer(big) |> lt_serve() }# rows stay in R; the browser fetches one page at a time (needs a live session) if (interactive()) { big = data.frame(id = 1:1e6, x = rnorm(1e6), g = sample(letters, 1e6, TRUE)) lt_viewer(big) |> lt_serve() }
A spanner is a label rendered above a contiguous group of column headers.
lt_spanner(x, label, columns, sep = "[._]")lt_spanner(x, label, columns, sep = "[._]")
x |
An |
label |
A character scalar — the spanner text. Alternatively, a
two-sided formula |
columns |
Columns to span: character names, integer positions, or a
one-sided formula (predicate formulas such as |
sep |
Separator pattern for auto-inference (default |
When called with no label or columns, infers spanners from column
names by splitting on the first . or _ separator. Contiguous columns
sharing a prefix are grouped under that prefix, and column labels are
shortened to the suffix.
x with the spanner recorded.
The columns must be contiguous in the body of the table.
tbl = lt(iris[1:3, ]) # a formula gives the label (LHS) and the columns (RHS) tbl |> lt_spanner(Sepal ~ Sepal.Length + Sepal.Width) # or the label and the columns separately; raw HTML label (wrap in I()) tbl |> lt_spanner(I("<em>Petal</em>"), ~ Petal.Length + Petal.Width) # infer spanners from shared prefixes tbl |> lt_spanner() # ... split at another separator d = data.frame(`Sales:Q1` = 1:2, `Sales:Q2` = 3:4, `Cost:Q1` = 5:6, check.names = FALSE) lt(d) |> lt_spanner(sep = ":")tbl = lt(iris[1:3, ]) # a formula gives the label (LHS) and the columns (RHS) tbl |> lt_spanner(Sepal ~ Sepal.Length + Sepal.Width) # or the label and the columns separately; raw HTML label (wrap in I()) tbl |> lt_spanner(I("<em>Petal</em>"), ~ Petal.Length + Petal.Width) # infer spanners from shared prefixes tbl |> lt_spanner() # ... split at another separator d = data.frame(`Sales:Q1` = 1:2, `Sales:Q2` = 3:4, `Cost:Q1` = 5:6, check.names = FALSE) lt(d) |> lt_spanner(sep = ":")
Render a per-row series of numbers as a small inline SVG line or bar chart (a
sparkline). The series for each row can come from a single list-column (each
element a numeric vector) or from several numeric columns read across the
row. Like lt_errorbar(), it is lightweight: only the numbers travel to the
client and the SVG is drawn in the browser, so an interactive table
(lt_interactive()) draws only the rows on the current page.
lt_sparkline( x, columns, type = c("line", "bar"), limits = NULL, color = NULL, width = 120, height = 20, hide = TRUE )lt_sparkline( x, columns, type = c("line", "bar"), limits = NULL, color = NULL, width = 120, height = 20, hide = TRUE )
x |
An |
columns |
The column(s) holding each row's series. Either a single
list-column (a one-sided formula |
type |
|
limits |
Numeric |
color |
CSS color for the line or bars (defaults to the stylesheet's). |
width, height
|
Pixel size of each cell's SVG. |
hide |
If |
x with the sparkline column recorded.
# a list-column: each cell is a numeric vector d = data.frame(city = c("A", "B", "C")) d$temp = list(c(3, 5, 8, 6, 9), c(1, 2, 2, 4, 3), c(7, 6, 5, 6, 8)) lt(d) |> lt_sparkline(~ temp) # bars, a color, a shared vertical scale (so rows are comparable), and a size lt(d) |> lt_sparkline( ~ temp, type = "bar", color = "#4caf50", limits = c(0, 10), width = 200, height = 30 ) # several columns read across the row (later ones hidden, or kept visible) m = data.frame(name = c("X", "Y"), q1 = c(2, 5), q2 = c(4, 3), q3 = c(6, 7)) lt(m) |> lt_sparkline(~ q1 + q2 + q3) lt(m) |> lt_sparkline(~ q1 + q2 + q3, hide = FALSE)# a list-column: each cell is a numeric vector d = data.frame(city = c("A", "B", "C")) d$temp = list(c(3, 5, 8, 6, 9), c(1, 2, 2, 4, 3), c(7, 6, 5, 6, 8)) lt(d) |> lt_sparkline(~ temp) # bars, a color, a shared vertical scale (so rows are comparable), and a size lt(d) |> lt_sparkline( ~ temp, type = "bar", color = "#4caf50", limits = c(0, 10), width = 200, height = 30 ) # several columns read across the row (later ones hidden, or kept visible) m = data.frame(name = c("X", "Y"), q1 = c(2, 5), q2 = c(4, 3), q3 = c(6, 7)) lt(m) |> lt_sparkline(~ q1 + q2 + q3) lt(m) |> lt_sparkline(~ q1 + q2 + q3, hide = FALSE)
Return the JSON-ready spec for an lt() table: the raw data plus the
declarative ops (and any lt_interactive() options), prepared exactly as the
JavaScript runtime expects. This is the payload the runtime consumes, so
another widget can embed an lt table by shipping this spec (e.g.
xfun::tojson(lt_spec(x))) and rendering it client-side on demand with
LT.render(container, spec) (or LT.buildHtml(spec)). Stylesheets
added by lt_css() are dropped; attach the runtime assets separately
(see lt_dependency()).
lt_spec(x)lt_spec(x)
x |
An |
A named list of spec fields (data, ops, and any others set on the
table), ready to serialize to JSON.
spec = lt(ToothGrowth[1:3, ]) |> lt_header("Guinea pigs") |> lt_spec() str(spec, max.level = 1) # ship this, then LT.render(container, spec) in the browser xfun::tojson(spec)spec = lt(ToothGrowth[1:3, ]) |> lt_header("Guinea pigs") |> lt_spec() str(spec, max.level = 1) # ship this, then LT.render(container, spec) in the browser xfun::tojson(spec)
Apply CSS styling to specific cells. Target cells by column, row, or both.
When test is provided, styles are applied conditionally based on cell
values (evaluated in JavaScript).
lt_style( x, columns = NULL, rows = NULL, test = NULL, class = NULL, bold = NULL, italic = NULL, color = NULL, bg = NULL, ... )lt_style( x, columns = NULL, rows = NULL, test = NULL, class = NULL, bold = NULL, italic = NULL, color = NULL, bg = NULL, ... )
x |
An |
columns |
Character names, integer positions, a one-sided formula
(predicate formulas such as |
rows |
Integer vector of 1-based row indices (or |
test |
A JavaScript function as a string (e.g., |
class |
CSS class name(s) to add to matching cells. Define the
corresponding rules in an external stylesheet via |
bold |
Logical: apply bold weight? |
italic |
Logical: apply italic style? |
color |
Text color (any CSS color value, e.g., |
bg |
Background color. |
... |
Additional CSS properties as named arguments. Names can be
camelCase (e.g., |
x with the style recorded.
d = trees[1:4, ] # inline styles on chosen rows and columns, plus any CSS property lt(d) |> lt_style(~ Girth, rows = 1, bold = TRUE, italic = TRUE, color = "#06c") |> lt_style(~ Height, bg = "#ffd", borderBottom = "2px solid red") # all cells, when columns is omitted lt(d) |> lt_style(color = "gray") # a JavaScript test picks the cells; a class keeps the rules in lt_css() lt(d) |> lt_style(~ Girth, test = "v => v > 8.5", class = "high") |> lt_css(.high = list(background = "#cfc"))d = trees[1:4, ] # inline styles on chosen rows and columns, plus any CSS property lt(d) |> lt_style(~ Girth, rows = 1, bold = TRUE, italic = TRUE, color = "#06c") |> lt_style(~ Height, bg = "#ffd", borderBottom = "2px solid red") # all cells, when columns is omitted lt(d) |> lt_style(color = "gray") # a JavaScript test picks the cells; a class keeps the rules in lt_css() lt(d) |> lt_style(~ Girth, test = "v => v > 8.5", class = "high") |> lt_css(.high = list(background = "#cfc"))
Replace NA, zero, or small values with display text.
lt_sub( x, columns = NULL, missing = NULL, zero = NULL, small = NULL, small_text = NULL )lt_sub( x, columns = NULL, missing = NULL, zero = NULL, small = NULL, small_text = NULL )
x |
An |
columns |
Character names, integer positions, a one-sided formula
(predicate formulas such as |
missing |
Replacement for |
zero |
Replacement for zero values (e.g., |
small |
Threshold: values whose absolute value is below this are
replaced by |
small_text |
Text shown for values below |
x with the substitution recorded.
d = data.frame( metric = c("HR", "p-value", "Events", "Rate"), value = c(0.62, 0.0003, 0, NA), other = c(NA, 0, 5, 1) ) # all columns: custom text for NA, zero, and tiny values lt(d) |> lt_sub(missing = "n/a", zero = "—", small = 0.001, small_text = "< 0.001") # only chosen columns lt(d) |> lt_sub(~ value, missing = "n/a")d = data.frame( metric = c("HR", "p-value", "Events", "Rate"), value = c(0.62, 0.0003, 0, NA), other = c(NA, 0, 5, 1) ) # all columns: custom text for NA, zero, and tiny values lt(d) |> lt_sub(missing = "n/a", zero = "—", small = 0.001, small_text = "< 0.001") # only chosen columns lt(d) |> lt_sub(~ value, missing = "n/a")
Append rows that summarize the data: one after each group, a grand summary
for the whole table, or both. A summary is whatever fn computes from a data
frame, so a sum, a weighted mean, or a count are all the same call.
lt_summary( x, fn = NULL, cols = NULL, by = NULL, label = NULL, grand = NULL, label_col = NULL, data_fn = NULL )lt_summary( x, fn = NULL, cols = NULL, by = NULL, label = NULL, grand = NULL, label_col = NULL, data_fn = NULL )
x |
An |
fn |
A function (or its name, such as |
cols |
The columns that |
by |
A column name or one-sided formula (e.g., |
label |
The text of a group summary row, shown in |
grand |
The text of the grand summary row at the bottom; |
label_col |
The column that shows |
data_fn |
A function that takes a data frame (the rows of one group, or of the whole table) and returns the summary values as a named list or data frame of one row. Columns it does not return are left empty. Use this to combine several columns, e.g., a weighted mean. |
Summary rows are shown in bold. A group summary closes its group. The grand
summary sits at the bottom of the table. In an interactive table (see
lt_interactive()), summary rows are not sorted, filtered, or counted as
matches: a group summary follows its group's rows through sorting and
disappears with the group when a filter removes all of its rows, while the
grand summary stays put. The values are computed once, from all rows, and do
not change as the table is filtered.
Call lt_summary() before functions that refer to rows by position
(e.g., lt_style() with rows), because summary rows shift the positions of
the rows after them. Combine it with lt_group() on the same column as by
so that each group's rows stay together.
x with the summary rows added.
d = data.frame( grp = c("A", "A", "B", "B"), item = c("x", "y", "x", "y"), n = c(10, 30, 20, 40), rate = c(0.12, 0.34, 0.56, 0.78) ) # a function (or its name) for every numeric column, after each group + total lt(d) |> lt_group(~ grp, sep = TRUE) |> lt_summary("sum", by = ~ grp) # a grand summary only, with a different function per column lt(d) |> lt_summary(list(n = sum, rate = "mean")) # chosen columns, custom labels, shown in a chosen column; no grand row lt(d) |> lt_summary( "max", ~ n, by = ~ grp, label = "Peak", grand = FALSE, label_col = "item" ) # a function of the whole data frame, for a weighted mean total = function(x) list(n = sum(x$n), rate = weighted.mean(x$rate, x$n)) lt(d) |> lt_summary(data_fn = total, by = ~ grp, grand = "All") |> lt_group(~ grp, sep = TRUE) |> lt_format(~ rate, percent = TRUE, decimals = 1)d = data.frame( grp = c("A", "A", "B", "B"), item = c("x", "y", "x", "y"), n = c(10, 30, 20, 40), rate = c(0.12, 0.34, 0.56, 0.78) ) # a function (or its name) for every numeric column, after each group + total lt(d) |> lt_group(~ grp, sep = TRUE) |> lt_summary("sum", by = ~ grp) # a grand summary only, with a different function per column lt(d) |> lt_summary(list(n = sum, rate = "mean")) # chosen columns, custom labels, shown in a chosen column; no grand row lt(d) |> lt_summary( "max", ~ n, by = ~ grp, label = "Peak", grand = FALSE, label_col = "item" ) # a function of the whole data frame, for a weighted mean total = function(x) list(n = sum(x$n), rate = weighted.mean(x$rate, x$n)) lt(d) |> lt_summary(data_fn = total, by = ~ grp, grand = "All") |> lt_group(~ grp, sep = TRUE) |> lt_format(~ rate, percent = TRUE, decimals = 1)
A data viewer: a shorthand for
lt_interactive(lt(data, show_types = TRUE), profile = TRUE, hide = NA)
with the data expression as the title, made by lt_header(). Each column
shows its type and a profile of its values, and the table can be sorted,
searched, filtered, paged, resized, and have columns hidden from a menu.
Printing the result at the console opens it in the viewer or browser. Use
|> lt_header(NULL) to remove the title.
lt_viewer(data, profile = TRUE, hide = NA, ...)lt_viewer(data, profile = TRUE, hide = NA, ...)
data |
A data frame. |
profile, hide, ...
|
Arguments passed to |
An lt_tbl object.
lt_viewer(CO2) # extra arguments go to lt_interactive(); no profiles, 5 rows per page lt_viewer(airquality, profile = FALSE, pager = 5)lt_viewer(CO2) # extra arguments go to lt_interactive(); no profiles, 5 rows per page lt_viewer(airquality, profile = FALSE, pager = 5)
Set column and table widths
lt_width(x, ...)lt_width(x, ...)
x |
An |
... |
Named arguments of the form |
x with the widths recorded.
d = trees[1:3, ] # an unnamed value sets the whole table's width; named ones set columns (any # CSS unit) lt(d) |> lt_width("60%", Girth = "40%", Height = "5em") # a list of two parallel vectors: names and widths lt(d) |> lt_width(list(c("Girth", "Height"), c("8em", "50px")))d = trees[1:3, ] # an unnamed value sets the whole table's width; named ones set columns (any # CSS unit) lt(d) |> lt_width("60%", Girth = "40%", Height = "5em") # a list of two parallel vectors: names and widths lt(d) |> lt_width(list(c("Girth", "Height"), c("8em", "50px")))
Set arbitrary HTML attributes on the <div class="lt-wrap"> that wraps the
rendered table (e.g. style, id, data-*). A class is appended to the
base lt-wrap class rather than replacing it, and accumulates across repeated
calls. Common uses are scoping custom CSS (e.g. attached with lt_css()) to
this table alone, or giving the container a fixed width.
lt_wrap(x, ...)lt_wrap(x, ...)
x |
An |
... |
Named HTML attributes for the container, e.g. |
x with the container attributes recorded.
tbl = lt(women[1:3, ]) tbl |> lt_wrap(style = "width: 300px;", class = "my-table")tbl = lt(women[1:3, ]) tbl |> lt_wrap(style = "width: 300px;", class = "my-table")
lt_tbl (opens in the viewer or browser)Print an lt_tbl (opens in the viewer or browser)
## S3 method for class 'lt_tbl' print(x, ...)## S3 method for class 'lt_tbl' print(x, ...)
x |
An |
... |
Passed to |
x, invisibly.
print(lt(ToothGrowth[1:3, ]))print(lt(ToothGrowth[1:3, ]))