Type: Package
Title: Exploratory Web Apps for Analyzing Clinical Trials Data
Version: 0.16.0
Date: 2025-02-12
Description: A 'shiny' based interactive exploration framework for analyzing clinical trials data. 'teal' currently provides a dynamic filtering facility and different data viewers. 'teal' 'shiny' applications are built using standard 'shiny' modules.
License: Apache License 2.0
URL: https://insightsengineering.github.io/teal/, https://github.com/insightsengineering/teal/
BugReports: https://github.com/insightsengineering/teal/issues
Depends: R (≥ 4.1), shiny (≥ 1.8.1), teal.data (≥ 0.7.0), teal.slice (≥ 0.6.0)
Imports: checkmate (≥ 2.1.0), cli, htmltools, jsonlite, lifecycle (≥ 0.2.0), logger (≥ 0.2.0), methods, rlang (≥ 1.0.0), shinyjs, stats, teal.code (≥ 0.6.1), teal.logger (≥ 0.3.2), teal.reporter (≥ 0.4.0), teal.widgets (≥ 0.4.3), tools, utils
Suggests: bslib, ggplot2 (≥ 3.4.0), knitr (≥ 1.42), mirai (≥ 1.1.1), MultiAssayExperiment, R6, renv (≥ 1.0.11), rmarkdown (≥ 2.23), roxy.shinylive, rvest (≥ 1.0.0), shinytest2, shinyvalidate, testthat (≥ 3.2.0), withr (≥ 2.1.0), yaml (≥ 1.1.0)
VignetteBuilder: knitr, rmarkdown
RdMacros: lifecycle
Config/Needs/verdepcheck: rstudio/shiny, insightsengineering/teal.data, insightsengineering/teal.slice, mllg/checkmate, jeroen/jsonlite, r-lib/lifecycle, daroczig/logger, shikokuchuo/mirai, r-lib/cli, shikokuchuo/nanonext, rstudio/renv, r-lib/rlang, daattali/shinyjs, insightsengineering/teal.code, insightsengineering/teal.logger, insightsengineering/teal.reporter, insightsengineering/teal.widgets, rstudio/bslib, yihui/knitr, bioc::MultiAssayExperiment, r-lib/R6, rstudio/rmarkdown, tidyverse/rvest, rstudio/shinytest2, rstudio/shinyvalidate, r-lib/testthat, r-lib/withr, yaml=vubiostat/r-yaml, rstudio/htmltools, bioc::matrixStats, insightsengineering/roxy.shinylive
Config/Needs/website: insightsengineering/nesttemplate
Encoding: UTF-8
Language: en-US
RoxygenNote: 7.3.2
Collate: 'TealAppDriver.R' 'checkmate.R' 'dummy_functions.R' 'include_css_js.R' 'modules.R' 'init.R' 'landing_popup_module.R' 'module_bookmark_manager.R' 'module_data_summary.R' 'module_filter_data.R' 'module_filter_manager.R' 'module_init_data.R' 'module_nested_tabs.R' 'module_session_info.R' 'module_snapshot_manager.R' 'module_teal.R' 'module_teal_data.R' 'module_teal_lockfile.R' 'module_teal_with_splash.R' 'module_transform_data.R' 'reporter_previewer_module.R' 'show_rcode_modal.R' 'tdata.R' 'teal.R' 'teal_data_module.R' 'teal_data_module-eval_code.R' 'teal_data_module-within.R' 'teal_data_utils.R' 'teal_modifiers.R' 'teal_reporter.R' 'teal_slices-store.R' 'teal_slices.R' 'teal_transform_module.R' 'utils.R' 'validate_inputs.R' 'validations.R' 'zzz.R'
NeedsCompilation: no
Packaged: 2025-02-18 20:11:07 UTC; unardid
Author: Dawid Kaledkowski ORCID iD [aut, cre], Pawel Rucki [aut], Aleksander Chlebowski ORCID iD [aut], Andre Verissimo ORCID iD [aut], Kartikeya Kirar [aut], Vedha Viyash [aut], Marcin Kosinski [aut], Adrian Waddell [aut], Chendi Liao [rev], Dony Unardi [rev], Nikolas Burkoff [aut], Mahmoud Hallal [aut], Maciej Nasinski [aut], Konrad Pagacz [aut], Junlue Zhao [aut], Tadeusz Lewandowski [aut], F. Hoffmann-La Roche AG [cph, fnd], Maximilian Mordig [ctb]
Maintainer: Dawid Kaledkowski <dawid.kaledkowski@roche.com>
Repository: CRAN
Date/Publication: 2025-02-23 17:00:02 UTC

teal: Interactive exploration of clinical trials data

Description

The teal package provides a shiny based framework for creating an interactive data analysis environment.

Details

To learn mode about the package, visit the project website or read the init() manual page.

Author(s)

Maintainer: Dawid Kaledkowski dawid.kaledkowski@roche.com (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Adds signature protection to the datanames in the data

Description

Adds signature protection to the datanames in the data

Usage

.add_signature_to_data(data)

Arguments

data

(teal_data)

Value

teal_data with additional code that has signature of the datanames


Calls expression when condition is met

Description

Function postpones handlerExpr to the moment when eventExpr (condition) returns TRUE, otherwise nothing happens.

Usage

.call_once_when(
  eventExpr,
  handlerExpr,
  event.env = parent.frame(),
  handler.env = parent.frame(),
  ...
)

Arguments

eventExpr

A (quoted or unquoted) logical expression that represents the event; this can be a simple reactive value like input$click, a call to a reactive expression like dataset(), or even a complex expression inside curly braces.

handlerExpr

The expression to call whenever eventExpr is invalidated. This should be a side-effect-producing action (the return value will be ignored). It will be executed within an isolate() scope.

event.env

The parent environment for the reactive expression. By default, this is the calling environment, the same as when defining an ordinary non-reactive expression. If eventExpr is a quosure and event.quoted is TRUE, then event.env is ignored.

handler.env

The parent environment for the reactive expression. By default, this is the calling environment, the same as when defining an ordinary non-reactive expression. If handlerExpr is a quosure and handler.quoted is TRUE, then handler.env is ignored.

...

additional arguments passed to observeEvent with the exception of eventExpr that is not allowed.

Value

An observer.


Get code that tests the integrity of the reproducible data

Description

Get code that tests the integrity of the reproducible data

Usage

.get_hashes_code(data, datanames = names(data))

Arguments

data

(teal_data) object holding the data

datanames

(character) names of datasets

Value

A character vector with the code lines.


Smart rbind

Description

Combine data.frame objects which have different columns

Usage

.smart_rbind(...)

Arguments

...

(data.frame)


The default favicon for the teal app.

Description

The default favicon for the teal app.

Usage

.teal_favicon

Format

An object of class character of length 1.


Drive a teal application

Description

Drive a teal application

Drive a teal application

Details

Extension of the shinytest2::AppDriver class with methods for driving a teal application for performing interactions for shinytest2 tests.

Super class

shinytest2::AppDriver -> TealAppDriver

Methods

Public methods

Inherited methods

Method new()

Initialize a TealAppDriver object for testing a teal application.

Usage
TealAppDriver$new(
  data,
  modules,
  filter = teal_slices(),
  title_args = list(),
  header = tags$p(),
  footer = tags$p(),
  landing_popup_args = NULL,
  timeout = rlang::missing_arg(),
  load_timeout = rlang::missing_arg(),
  ...
)
Arguments
data, modules, filter

arguments passed to init

title_args, header, footer, landing_popup_args

to pass into the modifier functions.

timeout

(numeric) Default number of milliseconds for any timeout or timeout_ parameter in the TealAppDriver class. Defaults to 20s.

See shinytest2::AppDriver new method for more details on how to change it via options or environment variables.

load_timeout

(numeric) How long to wait for the app to load, in ms. This includes the time to start R. Defaults to 100s.

See shinytest2::AppDriver new method for more details on how to change it via options or environment variables

...

Additional arguments to be passed to shinytest2::AppDriver$new

Returns

Object of class TealAppDriver


Method click()

Append parent shinytest2::AppDriver click method with a call to waif_for_idle() method.

Usage
TealAppDriver$click(...)
Arguments
...

arguments passed to parent shinytest2::AppDriver click() method.


Method expect_no_shiny_error()

Check if the app has shiny errors. This checks for global shiny errors. Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab is visited because shiny will not trigger server computations when the tab is invisible. So, navigate to the module tab you want to test before calling this function. Although, this catches errors hidden in the other module tabs if they are already rendered.

Usage
TealAppDriver$expect_no_shiny_error()

Method expect_no_validation_error()

Check if the app has no validation errors. This checks for global shiny validation errors.

Usage
TealAppDriver$expect_no_validation_error()

Method expect_validation_error()

Check if the app has validation errors. This checks for global shiny validation errors.

Usage
TealAppDriver$expect_validation_error()

Method set_input()

Set the input in the teal app.

Usage
TealAppDriver$set_input(input_id, value, ...)
Arguments
input_id

(character) The shiny input id with it's complete name space.

value

The value to set the input to.

...

Additional arguments to be passed to shinytest2::AppDriver$set_inputs

Returns

The TealAppDriver object invisibly.


Method navigate_teal_tab()

Navigate the teal tabs in the teal app.

Usage
TealAppDriver$navigate_teal_tab(tabs)
Arguments
tabs

(character) Labels of tabs to navigate to. The order of the tabs is important, and it should start with the most parent level tab. Note: In case the teal tab group has duplicate names, the first tab will be selected, If you wish to select the second tab with the same name, use the suffix "_1". If you wish to select the third tab with the same name, use the suffix "_2" and so on.

Returns

The TealAppDriver object invisibly.


Method active_ns()

Get the active shiny name space for different components of the teal app.

Usage
TealAppDriver$active_ns()
Returns

(list) The list of active shiny name space of the teal components.


Method active_module_ns()

Get the active shiny name space for interacting with the module content.

Usage
TealAppDriver$active_module_ns()
Returns

(string) The active shiny name space of the component.


Method active_module_element()

Get the active shiny name space bound with a custom element name.

Usage
TealAppDriver$active_module_element(element)
Arguments
element

character(1) custom element name.

Returns

(string) The active shiny name space of the component bound with the input element.


Method active_module_element_text()

Get the text of the active shiny name space bound with a custom element name.

Usage
TealAppDriver$active_module_element_text(element)
Arguments
element

character(1) the text of the custom element name.

Returns

(string) The text of the active shiny name space of the component bound with the input element.


Method active_filters_ns()

Get the active shiny name space for interacting with the filter panel.

Usage
TealAppDriver$active_filters_ns()
Returns

(string) The active shiny name space of the component.


Method active_data_summary_ns()

Get the active shiny name space for interacting with the data-summary panel.

Usage
TealAppDriver$active_data_summary_ns()
Returns

(string) The active shiny name space of the data-summary component.


Method active_data_summary_element()

Get the active shiny name space bound with a custom element name.

Usage
TealAppDriver$active_data_summary_element(element)
Arguments
element

character(1) custom element name.

Returns

(string) The active shiny name space of the component bound with the input element.


Method get_active_module_input()

Get the input from the module in the teal app. This function will only access inputs from the name space of the current active teal module.

Usage
TealAppDriver$get_active_module_input(input_id)
Arguments
input_id

(character) The shiny input id to get the value from.

Returns

The value of the shiny input.


Method get_active_module_output()

Get the output from the module in the teal app. This function will only access outputs from the name space of the current active teal module.

Usage
TealAppDriver$get_active_module_output(output_id)
Arguments
output_id

(character) The shiny output id to get the value from.

Returns

The value of the shiny output.


Method get_active_module_table_output()

Get the output from the module's teal.widgets::table_with_settings or DT::DTOutput in the teal app. This function will only access outputs from the name space of the current active teal module.

Usage
TealAppDriver$get_active_module_table_output(table_id, which = 1)
Arguments
table_id

(character(1)) The id of the table in the active teal module's name space.

which

(integer) If there is more than one table, which should be extracted. By default it will look for a table that is built using teal.widgets::table_with_settings.

Returns

The data.frame with table contents.


Method get_active_module_plot_output()

Get the output from the module's teal.widgets::plot_with_settings in the teal app. This function will only access plots from the name space of the current active teal module.

Usage
TealAppDriver$get_active_module_plot_output(plot_id)
Arguments
plot_id

(character(1)) The id of the plot in the active teal module's name space.

Returns

The src attribute as character(1) vector.


Method set_active_module_input()

Set the input in the module in the teal app. This function will only set inputs in the name space of the current active teal module.

Usage
TealAppDriver$set_active_module_input(input_id, value, ...)
Arguments
input_id

(character) The shiny input id to get the value from.

value

The value to set the input to.

...

Additional arguments to be passed to shinytest2::AppDriver$set_inputs

Returns

The TealAppDriver object invisibly.


Method get_active_filter_vars()

Get the active datasets that can be accessed via the filter panel of the current active teal module.

Usage
TealAppDriver$get_active_filter_vars()

Method get_active_data_summary_table()

Get the active data summary table

Usage
TealAppDriver$get_active_data_summary_table()
Returns

data.frame


Method is_visible()

Test if DOM elements are visible on the page with a JavaScript call.

Usage
TealAppDriver$is_visible(
  selector,
  content_visibility_auto = FALSE,
  opacity_property = FALSE,
  visibility_property = FALSE
)
Arguments
selector

(character(1)) CSS selector to check visibility. A CSS id will return only one element if the UI is well formed.

content_visibility_auto, opacity_property, visibility_property

(logical(1)) See more information on https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility.

Returns

Logical vector with all occurrences of the selector.


Method get_active_data_filters()

Get the active filter variables from a dataset in the teal app.

Usage
TealAppDriver$get_active_data_filters(dataset_name = NULL)
Arguments
dataset_name

(character) The name of the dataset to get the filter variables from. If NULL, the filter variables for all the datasets will be returned in a list.


Method add_filter_var()

Add a new variable from the dataset to be filtered.

Usage
TealAppDriver$add_filter_var(dataset_name, var_name, ...)
Arguments
dataset_name

(character) The name of the dataset to add the filter variable to.

var_name

(character) The name of the variable to add to the filter panel.

...

Additional arguments to be passed to shinytest2::AppDriver$set_inputs

Returns

The TealAppDriver object invisibly.


Method remove_filter_var()

Remove an active filter variable of a dataset from the active filter variables panel.

Usage
TealAppDriver$remove_filter_var(dataset_name = NULL, var_name = NULL)
Arguments
dataset_name

(character) The name of the dataset to remove the filter variable from. If NULL, all the filter variables will be removed.

var_name

(character) The name of the variable to remove from the filter panel. If NULL, all the filter variables of the dataset will be removed.

Returns

The TealAppDriver object invisibly.


Method set_active_filter_selection()

Set the active filter values for a variable of a dataset in the active filter variable panel.

Usage
TealAppDriver$set_active_filter_selection(dataset_name, var_name, input, ...)
Arguments
dataset_name

(character) The name of the dataset to set the filter value for.

var_name

(character) The name of the variable to set the filter value for.

input

The value to set the filter to.

...

Additional arguments to be passed to shinytest2::AppDriver$set_inputs

Returns

The TealAppDriver object invisibly.


Method get_attr()

Extract html attribute (found by a selector).

Usage
TealAppDriver$get_attr(selector, attribute)
Arguments
selector

(character(1)) specifying the selector to be used to get the content of a specific node.

attribute

(character(1)) name of an attribute to retrieve from a node specified by selector.

Returns

The character vector.


Method get_html_rvest()

Wrapper around get_html that passes the output directly to rvest::read_html.

Usage
TealAppDriver$get_html_rvest(selector)
Arguments
selector

(character(1)) passed to get_html.

Returns

An XML document. Wrapper around get_url() method that opens the app in the browser.


Method open_url()

Usage
TealAppDriver$open_url()
Returns

Nothing. Opens the underlying teal app in the browser.


Method wait_for_active_module_value()

Waits until a specified input, output, or export value. This function serves as a wrapper around the wait_for_value method, providing a more flexible interface for waiting on different types of values within the active module namespace.

Usage
TealAppDriver$wait_for_active_module_value(
  input = rlang::missing_arg(),
  output = rlang::missing_arg(),
  export = rlang::missing_arg(),
  ...
)
Arguments
input, output, export

A name of an input, output, or export value. Only one of these parameters may be used.

...

Must be empty. Allows for parameter expansion. Parameter with additional value to passed in wait_for_value.


Method clone()

The objects of this class are cloneable with this method.

Usage
TealAppDriver$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


TealReportCard

Description

[Experimental] Child class of teal.reporter::ReportCard that is used for teal specific applications. In addition to the parent methods, it supports rendering teal specific elements such as the source code, the encodings panel content and the filter panel content as part of the meta data.

Super class

teal.reporter::ReportCard -> TealReportCard

Methods

Public methods

Inherited methods

Method append_src()

Appends the source code to the content meta data of this TealReportCard.

Usage
TealReportCard$append_src(src, ...)
Arguments
src

(character(1)) code as text.

...

any rmarkdown R chunk parameter and its value. But eval parameter is always set to FALSE.

Returns

Object of class TealReportCard, invisibly.

Examples
card <- TealReportCard$new()$append_src(
  "plot(iris)"
)
card$get_content()[[1]]$get_content()

Method append_fs()

Appends the filter state list to the content and metadata of this TealReportCard. If the filter state list has an attribute named formatted, it appends it to the card otherwise it uses the default yaml::as.yaml to format the list. If the filter state list is empty, nothing is appended to the content.

Usage
TealReportCard$append_fs(fs)
Arguments
fs

(teal_slices) object returned from teal_slices() function.

Returns

self, invisibly.


Method append_encodings()

Appends the encodings list to the content and metadata of this TealReportCard.

Usage
TealReportCard$append_encodings(encodings)
Arguments
encodings

(list) list of encodings selections of the teal app.

Returns

self, invisibly.

Examples
card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))
card$get_content()[[1]]$get_content()


Method clone()

The objects of this class are cloneable with this method.

Usage
TealReportCard$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


## ------------------------------------------------
## Method `TealReportCard$append_src`
## ------------------------------------------------

card <- TealReportCard$new()$append_src(
  "plot(iris)"
)
card$get_content()[[1]]$get_content()

## ------------------------------------------------
## Method `TealReportCard$append_encodings`
## ------------------------------------------------

card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))
card$get_content()[[1]]$get_content()


TealSlicesBlock

Description

Specialized TealSlicesBlock block for managing filter panel content in reports.

Super classes

teal.reporter::ContentBlock -> teal.reporter::TextBlock -> TealSlicesBlock

Methods

Public methods

Inherited methods

Method new()

Returns a TealSlicesBlock object.

Usage
TealSlicesBlock$new(content = teal_slices(), style = "verbatim")
Arguments
content

(teal_slices) object returned from teal_slices() function.

style

(character(1)) string specifying style to apply.

Details

Returns a TealSlicesBlock object with no content and no parameters.

Returns

Object of class TealSlicesBlock, invisibly.


Method set_content()

Sets content of this TealSlicesBlock. Sets content as YAML text which represents a list generated from teal_slices. The list displays limited number of fields from teal_slice objects, but this list is sufficient to conclude which filters were applied. When selected field in teal_slice object is a range, then it is displayed as a "min"

Usage
TealSlicesBlock$set_content(content)
Arguments
content

(teal_slices) object returned from teal_slices() function.

Returns

self, invisibly.


Method from_list()

Create the TealSlicesBlock from a list.

Usage
TealSlicesBlock$from_list(x)
Arguments
x

(⁠named list⁠) with two fields text and style. Use the get_available_styles method to get all possible styles.

Returns

self, invisibly.

Examples
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$from_list(list(text = "sth", style = "default"))


Method to_list()

Convert the TealSlicesBlock to a list.

Usage
TealSlicesBlock$to_list()
Returns

⁠named list⁠ with a text and style.

Examples
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$to_list()


Method clone()

The objects of this class are cloneable with this method.

Usage
TealSlicesBlock$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


## ------------------------------------------------
## Method `TealSlicesBlock$from_list`
## ------------------------------------------------

TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$from_list(list(text = "sth", style = "default"))


## ------------------------------------------------
## Method `TealSlicesBlock$to_list`
## ------------------------------------------------

TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$to_list()


Add a Landing Popup to teal Application

Description

Adds a landing popup to the teal app. This popup will be shown when the app starts. The dialog must be closed by the app user to proceed to the main application.

Usage

add_landing_modal(
  x,
  title = NULL,
  content = NULL,
  footer = modalButton("Accept"),
  ...
)

Arguments

x

(teal_app) A teal_app object created using the init function.

title

An optional title for the dialog.

content

(character(1), shiny.tag or shiny.tag.list) with the content of the popup.

footer

UI for footer. Use NULL for no footer.

...

Additional arguments to shiny::modalDialog().

Examples in Shinylive

example-1

Open in Shinylive

Examples

app <- init(
  data = teal_data(IRIS = iris, MTCARS = mtcars),
  modules = modules(example_module())
) |>
  add_landing_modal(
    title = "Welcome",
    content = "This is a landing popup.",
    buttons = modalButton("Accept")
  )

if (interactive()) {
  shinyApp(app$ui, app$server)
}

Append a teal_module to children of a teal_modules object

Description

Append a teal_module to children of a teal_modules object

Usage

append_module(modules, module)

Arguments

modules

(teal_modules)

module

(teal_module) object to be appended onto the children of modules

Value

A teal_modules object with module appended.


Compare bookmarks.

Description

Test if two bookmarks store identical state.

Usage

bookmarks_identical(book1, book2)

Arguments

book1, book2

bookmark directories stored in ⁠shiny_bookmarks/⁠; default to the two most recently modified directories

Details

input environments are compared one variable at a time and if not identical, values in both bookmarks are reported. States of datatables are stripped of the time element before comparing because the time stamp is always different. The contents themselves are not printed as they are large and the contents are not informative. Elements present in one bookmark and absent in the other are also reported. Differences are printed as messages.

values environments are compared with all.equal.

Value

Invisible NULL if bookmarks are identical or if there are no bookmarks to test. FALSE if inconsistencies are detected.

How to use

Open an application, change relevant inputs (typically, all of them), and create a bookmark. Then open that bookmark and immediately create a bookmark of that. If restoring bookmarks occurred properly, the two bookmarks should store the same state.


Build app title with favicon

Description

A helper function to create the browser title along with a logo.

Usage

build_app_title(
  title = "teal app",
  favicon =
    "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png"
)

Arguments

title

(character) The browser title for the teal app.

favicon

(character) The path for the icon for the title. The image/icon path can be remote or the static path accessible by shiny, like the ⁠www/⁠

Value

A shiny.tag containing the element that adds the title and logo to the shiny app.


Check datanames in filters

Description

This function checks whether datanames in filters correspond to those in data, returning character vector with error messages or TRUE if all checks pass.

Usage

check_filter_datanames(filters, datanames)

Arguments

filters

(teal_slices) object

datanames

(character) names of datasets available in the data object

Value

A character(1) containing error message or TRUE if validation passes.


Check datanames in modules

Description

These functions check if specified datanames in modules match those in the data object, returning error messages or TRUE for successful validation. Two functions return error message in different forms:

Usage

check_modules_datanames(modules, datanames)

check_reserved_datanames(datanames)

check_modules_datanames_html(modules, datanames)

Arguments

modules

(teal_modules) object

datanames

(character) names of datasets available in the data object

Value

TRUE if validation passes, otherwise character(1) or shiny.tag.list


Check that argument is reactive.

Description

Check that argument is reactive.

Usage

check_reactive(x, null.ok = FALSE)

test_reactive(x, null.ok = FALSE)

assert_reactive(
  x,
  null.ok = FALSE,
  .var.name = checkmate::vname(x),
  add = NULL
)

Arguments

x

[any]
Object to check.

null.ok

[logical(1)]
If set to TRUE, x may also be NULL. In this case only a type check of x is performed, all additional checks are disabled.

.var.name

[character(1)]
Name of the checked object to print in assertions. Defaults to the heuristic implemented in vname.

add

[AssertCollection]
Collection to store assertion messages. See AssertCollection.

Value

Depending on the function prefix: If the check is successful, the functions assertClass/assert_class return x invisibly, whereas checkClass/check_class and testClass/test_class return TRUE. If the check is not successful, assertClass/assert_class throws an error message, testClass/test_class returns FALSE, and checkClass/check_class return a string with the error message. The function expect_class always returns an expectation.


Application ID

Description

Creates App ID used to match filter snapshots to application.

Usage

create_app_id(data, modules)

Arguments

data

(teal_data or teal_data_module) as accepted by init

modules

(teal_modules) object as accepted by init

Details

Calculate app ID that will be used to stamp filter state snapshots. App ID is a hash of the app's data and modules. See "transferring snapshots" section in ?snapshot.

Value

A single character string.


Capture error and decorate error message.

Description

Capture error and decorate error message.

Usage

decorate_err_msg(x, pre = character(0), post = character(0))

Arguments

x

object to evaluate

pre

(character(1)) A string to prepend to error message

post

(character(1)) A string to append to error message

Value

x if no error, otherwise throws error with decorated message


Deep copy teal_slices

Description

it's important to create a new copy of teal_slices when starting a new shiny session. Otherwise, object will be shared by multiple users as it is created in global environment before shiny session starts.

Usage

deep_copy_filter(filter)

Arguments

filter

(teal_slices)

Value

teal_slices


An example teal module

Description

[Experimental]

Usage

example_module(
  label = "example teal module",
  datanames = "all",
  transformators = list(),
  decorators = list()
)

Arguments

label

(character(1)) Label shown in the navigation item for the module or module group. For modules() defaults to "root". See Details.

datanames

(character) Names of the datasets relevant to the item. There are 2 reserved values that have specific behaviors:

  • The keyword "all" includes all datasets available in the data passed to the teal application.

  • NULL hides the sidebar panel completely.

  • If transformators are specified, their datanames are automatically added to this datanames argument.

transformators

(list of teal_transform_module) that will be applied to transform module's data input. To learn more check vignette("transform-input-data", package = "teal").

decorators

[Experimental] (list of teal_transform_module) optional, decorator for object included in the module.

Details

This module creates an object called object that can be modified with decorators. The object is determined by what's selected in ⁠Choose a dataset⁠ input in UI. The object can be anything that can be handled by renderPrint(). See the vignette("transform-module-output", package = "teal") or teal_transform_module to read more about decorators.

Value

A teal module which can be included in the modules argument to init().

Examples in Shinylive

example-1

Open in Shinylive

Examples

app <- init(
  data = teal_data(IRIS = iris, MTCARS = mtcars),
  modules = example_module()
)
if (interactive()) {
  shinyApp(app$ui, app$server)
}

Extract/Remove module(s) of specific class

Description

Given a teal_module or a teal_modules, return the elements of the structure according to class.

Usage

extract_module(modules, class)

drop_module(modules, class)

Arguments

modules

(teal_modules)

class

The class name of teal_module to be extracted or dropped.

Value

teal_modules


Extract all transformators from modules.

Description

Extract all transformators from modules.

Usage

extract_transformators(modules)

Arguments

modules

teal_modules or teal_module

Value

A list of teal_transform_module nested in the same way as input modules.


Get client timezone

Description

User timezone in the browser may be different to the one on the server. This script can be run to register a shiny input which contains information about the timezone in the browser.

Usage

get_client_timezone(ns)

Arguments

ns

(function) namespace function passed from the session object in the shiny server. For shiny modules this will allow for proper name spacing of the registered input.

Value

NULL, invisibly.


Get unique labels

Description

Get unique labels for the modules to avoid namespace conflicts.

Usage

get_unique_labels(labels)

Arguments

labels

(character) vector of labels

Value

(character) vector of unique labels


Include CSS files from ⁠/inst/css/⁠ package directory to application header

Description

system.file should not be used to access files in other packages, it does not work with devtools. Therefore, we redefine this method in each package as needed. Thus, we do not export this method.

Usage

include_css_files(pattern = "*")

Arguments

pattern

(character) pattern of files to be included

Value

HTML code that includes CSS files.


Include JS files from ⁠/inst/js/⁠ package directory to application header

Description

system.file should not be used to access files in other packages, it does not work with devtools. Therefore, we redefine this method in each package as needed. Thus, we do not export this method

Usage

include_js_files(pattern = NULL, except = NULL)

Arguments

pattern

(character) pattern of files to be included, passed to system.file

except

(character) vector of basename filenames to be excluded

Value

HTML code that includes JS files.


Code to include teal CSS and JavaScript files

Description

This is useful when you want to use the same JavaScript and CSS files that are used with the teal application. This is also useful for running standalone modules in teal with the correct styles. Also initializes shinyjs so you can use it.

Usage

include_teal_css_js()

Details

Simply add include_teal_css_js() as one of the UI elements.

Value

A shiny.tag.list.


Create the server and UI function for the shiny app

Description

[Stable]

End-users: This is the most important function for you to start a teal app that is composed of teal modules.

Usage

init(
  data,
  modules,
  filter = teal_slices(),
  title = lifecycle::deprecated(),
  header = lifecycle::deprecated(),
  footer = lifecycle::deprecated(),
  id = lifecycle::deprecated()
)

Arguments

data

(teal_data or teal_data_module) For constructing the data object, refer to teal.data::teal_data() and teal_data_module().

modules

(list or teal_modules or teal_module) Nested list of teal_modules or teal_module objects or a single teal_modules or teal_module object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

filter

(teal_slices) Optionally, specifies the initial filter using teal_slices().

title

(shiny.tag or character(1)) [Deprecated] Optionally, the browser window title. Defaults to a title "teal app" with the icon of NEST. Can be created using the build_app_title() or by passing a valid shiny.tag which is a head tag with title and link tag. This parameter is no longer supported. Use modify_title() on the teal app object instead.

header

(shiny.tag or character(1)) [Deprecated] Optionally, the header of the app. This parameter is no longer supported. Use modify_header() on the teal app object instead.

footer

(shiny.tag or character(1)) [Deprecated] Optionally, the footer of the app. This parameter is no longer supported. Use modify_footer() on the teal app object instead.

id

[Deprecated] (character) Optionally, a string specifying the shiny module id in cases it is used as a shiny module rather than a standalone shiny app. This parameter is no longer supported. Use ui_teal() and srv_teal() instead.

Value

Named list containing server and UI functions.

Examples in Shinylive

example-1

Open in Shinylive

Examples

app <- init(
  data = within(
    teal_data(),
    {
      new_iris <- transform(iris, id = seq_len(nrow(iris)))
      new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))
    }
  ),
  modules = modules(
    module(
      label = "data source",
      server = function(input, output, session, data) {},
      ui = function(id, ...) tags$div(p("information about data source")),
      datanames = "all"
    ),
    example_module(label = "example teal module"),
    module(
      "Iris Sepal.Length histogram",
      server = function(input, output, session, data) {
        output$hist <- renderPlot(
          hist(data()[["new_iris"]]$Sepal.Length)
        )
      },
      ui = function(id, ...) {
        ns <- NS(id)
        plotOutput(ns("hist"))
      },
      datanames = "new_iris"
    )
  ),
  filter = teal_slices(
    teal_slice(dataname = "new_iris", varname = "Species"),
    teal_slice(dataname = "new_iris", varname = "Sepal.Length"),
    teal_slice(dataname = "new_mtcars", varname = "cyl"),
    exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),
    module_specific = TRUE,
    mapping = list(
      `example teal module` = "new_iris Species",
      `Iris Sepal.Length histogram` = "new_iris Species",
      global_filters = "new_mtcars cyl"
    )
  )
)
if (interactive()) {
  shinyApp(app$ui, app$server)
}


Does the object make use of the arg

Description

Does the object make use of the arg

Usage

is_arg_used(modules, arg)

Arguments

modules

(teal_module or teal_modules) object

arg

(character(1)) names of the arguments to be checked against formals of teal modules.

Value

logical whether the object makes use of arg.


Landing popup module

Description

[Deprecated] Creates a landing welcome popup for teal applications.

This module is used to display a popup dialog when the application starts. The dialog blocks access to the application and must be closed with a button before the application can be viewed. This function is deprecated, please use add_landing_modal() on the teal app object instead.

Usage

landing_popup_module(
  label = "Landing Popup",
  title = NULL,
  content = NULL,
  buttons = modalButton("Accept")
)

Arguments

label

(character(1)) Label of the module.

title

(character(1)) Text to be displayed as popup title.

content

(character(1), shiny.tag or shiny.tag.list) with the content of the popup. Passed to ... of shiny::modalDialog. See examples.

buttons

(shiny.tag or shiny.tag.list) Typically a modalButton or actionButton. See examples.

Value

A teal_module (extended with teal_landing_module class) to be used in teal applications.


Make teal_transform_module's server

Description

A factory function to simplify creation of a teal_transform_module's server. Specified expr is wrapped in a shiny module function and output can be passed to the server argument in teal_transform_module() call. Such a server function can be linked with ui and values from the inputs can be used in the expression. Object names specified in the expression will be substituted with the value of the respective input (matched by the name) - for example in expression(graph <- graph + ggtitle(title)) object title will be replaced with the value of input$title.

Usage

make_teal_transform_server(expr)

Arguments

expr

(language) An R call which will be evaluated within teal.data::teal_data environment.

Value

⁠function(id, data)⁠ returning shiny module

Examples in Shinylive

example-1

Open in Shinylive

Examples


trim_iris <- teal_transform_module(
  label = "Simplified interactive transformator for iris",
  datanames = "iris",
  ui = function(id) {
    ns <- NS(id)
    numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1)
  },
  server = make_teal_transform_server(expression(iris <- head(iris, n_rows)))
)

app <- init(
  data = teal_data(iris = iris),
  modules = example_module(transformators = trim_iris)
)
if (interactive()) {
  shinyApp(app$ui, app$server)
}


App state management.

Description

[Experimental]

Capture and restore the global (app) input state.

Usage

ui_bookmark_panel(id, modules)

srv_bookmark_panel(id, modules)

get_bookmarking_option()

need_bookmarking(modules)

Arguments

id

(character(1)) shiny module instance id.

modules

(teal_modules) teal_modules object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

Details

This module introduces bookmarks into teal apps: the shiny bookmarking mechanism becomes enabled and server-side bookmarks can be created.

The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.

teal does not guarantee that all modules (teal_module objects) are bookmarkable. Those that are, have a teal_bookmarkable attribute set to TRUE. If any modules are not bookmarkable, the bookmark manager modal displays a warning and the bookmark button displays a flag. In order to communicate that a external module is bookmarkable, the module developer should set the teal_bookmarkable attribute to TRUE.

Value

Invisible NULL.

Server logic

A bookmark is a URL that contains the app address with a ⁠/?_state_id_=<bookmark_dir>⁠ suffix. ⁠<bookmark_dir>⁠ is a directory created on the server, where the state of the application is saved. Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.

Note

To enable bookmarking use either:


Data summary

Description

Module and its utils to display the number of rows and subjects in the filtered and unfiltered data.

Usage

ui_data_summary(id)

srv_data_summary(id, data)

get_filter_overview_wrapper(teal_data)

get_filter_overview(current_data, initial_data, dataname, subject_keys)

get_filter_overview_array(current_data, initial_data, dataname, subject_keys)

get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname)

Arguments

id

(character(1)) shiny module instance id.

data

(reactive returning teal_data)

current_data

(object) current object (after filtering and transforming).

initial_data

(object) initial object.

dataname

(character(1))

subject_keys

(character) names of the columns which determine a single unique subjects

Details

Handling different data classes: get_filter_overview() is a pseudo S3 method which has variants for:

Module includes also "Show/Hide unsupported" button to toggle rows of the summary table containing datasets where number of observations are not calculated.

Value

NULL.


Filter panel module in teal

Description

Creates filter panel module from teal_data object and returns teal_data. It is build in a way that filter panel changes and anything what happens before (e.g. module_init_data) is triggering further reactive events only if something has changed and if the module is visible. Thanks to this special implementation all modules' data are recalculated only for those modules which are currently displayed.

Usage

ui_filter_data(id)

srv_filter_data(id, datasets, active_datanames, data, is_active)

.make_filtered_teal_data(modules, data, datasets = NULL, datanames)

.observe_active_filter_changed(datasets, is_active, active_datanames, data)

.get_filter_expr(datasets, datanames)

Arguments

id

(character(1)) shiny module instance id.

datasets

(reactive returning FilteredData or NULL) When datasets is passed from the parent module (srv_teal) then dataset is a singleton which implies in filter-panel to be "global". When NULL then filter-panel is "module-specific".

active_datanames

(reactive returning character) this module's data names

data

(reactive returning teal_data)

modules

(teal_modules) teal_modules object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

Value

A eventReactive containing teal_data containing filtered objects and filter code. eventReactive triggers only if all conditions are met:


Manage multiple FilteredData objects

Description

Oversee filter states across the entire application.

Usage

ui_filter_manager_panel(id)

srv_filter_manager_panel(id, slices_global)

ui_filter_manager(id)

srv_filter_manager(id, slices_global)

srv_module_filter_manager(id, module_fd, slices_global)

Arguments

id

(character(1)) shiny module instance id.

slices_global

(reactiveVal) containing teal_slices.

module_fd

(FilteredData) Object containing the data to be filtered in a single teal module.

Value

Module returns a slices_global (reactiveVal) containing a teal_slices object with mapping.

Slices global

The key role in maintaining the module-specific filter states is played by the .slicesGlobal object. It is a reference class that holds the following fields:

During a session only new filters are added to all_slices unless module_snapshot_manager is used to restore previous state. Filters from all_slices can be activated or deactivated in a module which is linked (both ways) by attr(, "mapping") so that:

Filter manager

Filter-manager is split into two parts:

  1. ui/srv_filter_manager_panel - Called once for the whole app. This module observes changes in the filters in slices_global and displays them in a table utilizing information from mapping:

  1. ui/srv_module_filter_manager - Called once for each teal_module. Handling filter states for of single module and keeping module FilteredData consistent with slices_global, so that local filters are always reflected in the slices_global and its mapping and vice versa.


Data Module for teal

Description

This module manages the data argument for srv_teal. The teal framework uses teal.data::teal_data(), which can be provided in various ways:

  1. Directly as a teal.data::teal_data() object. This will automatically convert it into a reactive teal_data.

  2. As a reactive object that returns a teal.data::teal_data() object.

Usage

ui_init_data(id)

srv_init_data(id, data)

Arguments

id

(character(1)) shiny module instance id.

data

(teal_data, teal_data_module, or reactive returning teal_data) The data which application will depend on.

Details

Reactive teal_data:

The data in the application can be reactively updated, prompting srv_teal() to rebuild the content accordingly. There are two methods for creating interactive teal_data:

  1. Using a reactive object provided from outside the teal application. In this scenario, reactivity is controlled by an external module, and srv_teal responds to changes.

  2. Using teal_data_module(), which is embedded within the teal application, allowing data to be resubmitted by the user as needed.

Since the server of teal_data_module() must return a reactive teal_data object, both methods (1 and 2) produce the same reactive behavior within a teal application. The distinction lies in data control: the first method involves external control, while the second method involves control from a custom module within the app.

For more details, see module_teal_data.

Value

A reactive object that returns: Output of the data. If data fails then returned error is handled (after tryCatch()) so that rest of the application can respond to this respectively.


Retrieve labels from teal_modules

Description

Retrieve labels from teal_modules

Usage

module_labels(modules)

Arguments

modules

(teal_modules)

Value

A list containing the labels of the modules. If the modules are nested, the function returns a nested list of labels.


teal user session info module

Description

Module to display the user session info popup and to download a lockfile. Module is included when running init() but skipped when using module_teal. Please be aware that session info contains R session information, so multiple module's calls will share the same information.

Usage

ui_session_info(id)

srv_session_info(id)

Arguments

id

(character(1)) shiny module instance id.

Value

NULL invisibly

Examples in Shinylive

example-1

Open in Shinylive

Examples

ui <- fluidPage(
  ui_session_info("session_info")
)

server <- function(input, output, session) {
  srv_session_info("session_info")
}

if (interactive()) {
  shinyApp(ui, server)
}


Filter state snapshot management

Description

Capture and restore snapshots of the global (app) filter state.

Usage

ui_snapshot_manager_panel(id)

srv_snapshot_manager_panel(id, slices_global)

ui_snapshot_manager(id)

srv_snapshot_manager(id, slices_global)

Arguments

id

(character(1)) shiny module instance id.

slices_global

(reactiveVal) that contains a teal_slices object containing all teal_slices existing in the app, both active and inactive.

Details

This module introduces snapshots: stored descriptions of the filter state of the entire application. Snapshots allow the user to save the current filter state of the application for later use in the session, as well as to save it to file in order to share it with an app developer or other users, who in turn can upload it to their own session.

The snapshot manager is accessed with the camera icon in the tabset bar. At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file and applies the filter states therein, and clicking the arrow resets initial application state. As snapshots are added, they will show up as rows in a table and each will have a select button and a save button.

Value

list containing the snapshot history, where each element is an unlisted teal_slices object.

Server logic

Snapshots are basically teal_slices objects, however, since each module is served by a separate instance of FilteredData and these objects require shared state, teal_slice is a reactiveVal so teal_slices cannot be stored as is. Therefore, teal_slices are reversibly converted to a list of lists representation (attributes are maintained).

Snapshots are stored in a reactiveVal as a named list. The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.

For every snapshot except the initial one, a piece of UI is generated that contains the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. The initial snapshot is restored by a separate "reset" button. It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.

Snapshot mechanics

When a snapshot is captured, the user is prompted to name it. Names are displayed as is but since they are used to create button ids, under the hood they are converted to syntactically valid strings. New snapshot names are validated so that their valid versions are unique. Leading and trailing white space is trimmed.

The module can read the global state of the application from slices_global and mapping_matrix. The former provides a list of all existing teal_slices and the latter says which slice is active in which module. Once a name has been accepted, slices_global is converted to a list of lists - a snapshot. The snapshot contains the mapping attribute of the initial application state (or one that has been restored), which may not reflect the current one, so mapping_matrix is transformed to obtain the current mapping, i.e. a list that, when passed to the mapping argument of teal_slices(), would result in the current mapping. This is substituted as the snapshot's mapping attribute and the snapshot is added to the snapshot list.

To restore app state, a snapshot is retrieved from storage and rebuilt into a teal_slices object. Then state of all FilteredData objects (provided in datasets) is cleared and set anew according to the mapping attribute of the snapshot. The snapshot is then set as the current content of slices_global.

To save a snapshot, the snapshot is retrieved and reassembled just like for restoring, and then saved to file with slices_store().

When a snapshot is uploaded, it will first be added to storage just like a newly created one, and then used to restore app state much like a snapshot taken from storage. Upon clicking the upload icon the user will be prompted for a file to upload and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped) and normal naming rules apply. Loading the file yields a teal_slices object, which is disassembled for storage and used directly for restoring app state.

Transferring snapshots

Snapshots uploaded from disk should only be used in the same application they come from, i.e. an application that uses the same data and the same modules. To ensure this is the case, init stamps teal_slices with an app id that is stored in the app_id attribute of a teal_slices object. When a snapshot is restored from file, its app_id is compared to that of the current app state and only if the match is the snapshot admitted to the session.

Bookmarks

An onBookmark callback creates a snapshot of the current filter state. This is done on the app session, not the module session. (The snapshot will be retrieved by module_teal in order to set initial app state in a restored app.) Then that snapshot, and the previous snapshot history are dumped into the values.rds file in ⁠<bookmark_dir>⁠.

Author(s)

Aleksander Chlebowski


teal main module

Description

[Stable] Module to create a teal app as a Shiny Module.

Usage

ui_teal(id, modules)

srv_teal(id, data, modules, filter = teal_slices())

Arguments

id

(character(1)) shiny module instance id.

modules

(teal_modules) teal_modules object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

data

(teal_data, teal_data_module, or reactive returning teal_data) The data which application will depend on.

filter

(teal_slices) Optionally, specifies the initial filter using teal_slices().

Details

This module can be used instead of init() in custom Shiny applications. Unlike init(), it doesn't automatically include module_session_info.

Module is responsible for creating the main shiny app layout and initializing all the necessary components. This module establishes reactive connection between the input data and every other component in the app. Reactive change of the data passed as an argument, reloads the app and possibly keeps all input settings the same so the user can continue where one left off.

data flow in teal application

This module supports multiple data inputs but eventually, they are all converted to reactive returning teal_data in this module. On this ⁠reactive teal_data⁠ object several actions are performed:

Fallback on failure

teal is designed in such way that app will never crash if the error is introduced in any custom shiny module provided by app developer (e.g. teal_data_module(), teal_transform_module()). If any module returns a failing object, the app will halt the evaluation and display a warning message. App user should always have a chance to fix the improper input and continue without restarting the session.

Value

NULL invisibly


Execute and validate teal_data_module

Description

This is a low level module to handle teal_data_module execution and validation. teal_transform_module() inherits from teal_data_module() so it is handled by this module too. srv_teal() accepts various data objects and eventually they are all transformed to reactive teal.data::teal_data() which is a standard data class in whole teal framework.

Usage

ui_teal_data_module(id, data_module = function(id) NULL)

srv_teal_data_module(
  id,
  data_module = function(id) NULL,
  modules = NULL,
  validate_shiny_silent_error = TRUE,
  is_transform_failed = reactiveValues()
)

ui_validate_reactive_teal_data(id)

srv_validate_reactive_teal_data(
  id,
  data,
  modules = NULL,
  validate_shiny_silent_error = FALSE,
  hide_validation_error = reactive(FALSE)
)

Arguments

id

(character(1)) shiny module instance id.

data_module

(teal_data_module)

modules

(teal_modules or teal_module) For datanames validation purpose

validate_shiny_silent_error

(logical) If TRUE, then shiny.silent.error is validated and

is_transform_failed

(reactiveValues) contains logical flags named after each transformator. Help to determine if any previous transformator failed, so that following transformators can be disabled and display a generic failure message.

data

(reactive returning teal_data)

Value

reactive teal_data

data validation

Executed teal_data_module() is validated and output is validated for consistency. Output data is invalid if:

  1. teal_data_module() is invalid if server doesn't return reactive. Immediately crashes an app!

  2. reactive throws a shiny.error - happens when module creating teal.data::teal_data() fails.

  3. reactive returns qenv.error - happens when teal.data::teal_data() evaluates a failing code.

  4. reactive object doesn't return teal.data::teal_data().

  5. teal.data::teal_data() object lacks any datanames specified in the modules argument.

teal (observers in srv_teal) always waits to render an app until reactive teal_data is returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is resolved, the app will continue to run. teal guarantees that errors in data don't crash the app (except error 1).

Note

ui_teal_data_module was renamed from ui_teal_data.

srv_teal_data_module was renamed from srv_teal_data.


Generate lockfile for application's environment reproducibility

Description

Generate lockfile for application's environment reproducibility

Usage

ui_teal_lockfile(id)

srv_teal_lockfile(id)

.teal_lockfile_process_invoke(lockfile_path)

.renv_snapshot(lockfile_path)

.is_lockfile_deps_installed()

.is_disabled_lockfile_scenario()

Arguments

id

(character(1)) shiny module instance id.

lockfile_path

(character) path to the lockfile.

Value

NULL

Different ways of creating lockfile

teal leverages renv::snapshot(), which offers multiple methods for lockfile creation.

lockfile usage

After creating the lockfile, you can restore the application's environment using renv::restore().

See Also

renv::snapshot(), renv::restore().


Calls all modules

Description

On the UI side each teal_modules is translated to a tabsetPanel and each teal_module is a tabPanel. Both, UI and server are called recursively so that each tab is a separate module and reflect nested structure of modules argument.

Usage

ui_teal_module(id, modules, depth = 0L)

## Default S3 method:
ui_teal_module(id, modules, depth = 0L)

## S3 method for class 'teal_modules'
ui_teal_module(id, modules, depth = 0L)

## S3 method for class 'teal_module'
ui_teal_module(id, modules, depth = 0L)

srv_teal_module(
  id,
  data,
  modules,
  datasets = NULL,
  slices_global,
  reporter = teal.reporter::Reporter$new(),
  data_load_status = reactive("ok"),
  is_active = reactive(TRUE)
)

## Default S3 method:
srv_teal_module(
  id,
  data,
  modules,
  datasets = NULL,
  slices_global,
  reporter = teal.reporter::Reporter$new(),
  data_load_status = reactive("ok"),
  is_active = reactive(TRUE)
)

## S3 method for class 'teal_modules'
srv_teal_module(
  id,
  data,
  modules,
  datasets = NULL,
  slices_global,
  reporter = teal.reporter::Reporter$new(),
  data_load_status = reactive("ok"),
  is_active = reactive(TRUE)
)

## S3 method for class 'teal_module'
srv_teal_module(
  id,
  data,
  modules,
  datasets = NULL,
  slices_global,
  reporter = teal.reporter::Reporter$new(),
  data_load_status = reactive("ok"),
  is_active = reactive(TRUE)
)

Arguments

id

(character(1)) shiny module instance id.

modules

(teal_modules) teal_modules object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

depth

(integer(1)) number which helps to determine depth of the modules nesting.

data

(reactive returning teal_data)

datasets

(reactive returning FilteredData or NULL) When datasets is passed from the parent module (srv_teal) then dataset is a singleton which implies in filter-panel to be "global". When NULL then filter-panel is "module-specific".

slices_global

(reactiveVal returning modules_teal_slices) see module_filter_manager

data_load_status

(reactive returning character) Determines action dependent on a data loading status:

  • "ok" when teal_data is returned from the data loading.

  • "teal_data_module failed" when teal_data_module() didn't return teal_data. Disables tabs buttons.

  • "external failed" when a reactive passed to srv_teal(data) didn't return teal_data. Hides the whole tab panel.

Value

output of currently active module.


UI and server modules of teal

Description

[Deprecated] Please use module_teal instead.

Usage

ui_teal_with_splash(
  id,
  data,
  modules,
  title = build_app_title(),
  header = tags$p(),
  footer = tags$p()
)

srv_teal_with_splash(id, data, modules, filter = teal_slices())

Arguments

id

(character(1)) shiny module instance id.

data

(teal_data, teal_data_module, or reactive returning teal_data) The data which application will depend on.

modules

(teal_modules) teal_modules object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

title

(shiny.tag or character(1)) [Deprecated] Optionally, the browser window title. Defaults to a title "teal app" with the icon of NEST. Can be created using the build_app_title() or by passing a valid shiny.tag which is a head tag with title and link tag. This parameter is no longer supported. Use modify_title() on the teal app object instead.

header

(shiny.tag or character(1)) [Deprecated] Optionally, the header of the app. This parameter is no longer supported. Use modify_header() on the teal app object instead.

footer

(shiny.tag or character(1)) [Deprecated] Optionally, the footer of the app. This parameter is no longer supported. Use modify_footer() on the teal app object instead.

filter

(teal_slices) Optionally, specifies the initial filter using teal_slices().

Value

Returns a reactive expression containing a teal_data object when data is loaded or NULL when it is not.


Module to transform reactive teal_data

Description

Module calls teal_transform_module() in sequence so that ⁠reactive teal_data⁠ output from one module is handed over to the following module's input.

Usage

ui_transform_teal_data(id, transformators, class = "well")

srv_transform_teal_data(
  id,
  data,
  transformators,
  modules = NULL,
  is_transform_failed = reactiveValues()
)

Arguments

id

(character(1)) shiny module instance id.

transformators

(list of teal_transform_module) that will be applied to transform module's data input. To learn more check vignette("transform-input-data", package = "teal").

class

(character(1)) CSS class to be added in the div wrapper tag.

data

(reactive returning teal_data)

modules

(teal_modules or teal_module) For datanames validation purpose

is_transform_failed

(reactiveValues) contains logical flags named after each transformator. Help to determine if any previous transformator failed, so that following transformators can be disabled and display a generic failure message.

Value

reactive teal_data


Retrieve teal_bookmarkable attribute from teal_modules

Description

Retrieve teal_bookmarkable attribute from teal_modules

Usage

modules_bookmarkable(modules)

Arguments

modules

(teal_modules or teal_module) object

Value

named list of the same structure as modules with TRUE or FALSE values indicating whether the module is bookmarkable.


Get module depth

Description

Depth starts at 0, so a single teal.module has depth 0. Nesting it increases overall depth by 1.

Usage

modules_depth(modules, depth = 0L)

Arguments

modules

(list or teal_modules or teal_module) Nested list of teal_modules or teal_module objects or a single teal_modules or teal_module object. These are the specific output modules which will be displayed in the teal application. See modules() and module() for more details.

depth

optional integer determining current depth level

Value

Depth level for given module.


Pluralize a word depending on the size of the input

Description

Pluralize a word depending on the size of the input

Usage

pluralize(x, singular, plural = NULL)

Arguments

x

(object) to check length for plural.

singular

(character) singular form of the word.

plural

(optional character) plural form of the word. If not given an "s" is added to the singular form.

Value

A character that correctly represents the size of the x argument.


Template function for TealReportCard creation and customization

Description

This function generates a report card with a title, an optional description, and the option to append the filter state list.

Usage

report_card_template(
  title,
  label,
  description = NULL,
  with_filter,
  filter_panel_api
)

Arguments

title

(character(1)) title of the card (unless overwritten by label)

label

(character(1)) label provided by the user when adding the card

description

(character(1)) optional, additional description

with_filter

(logical(1)) flag indicating to add filter state

filter_panel_api

(FilterPanelAPI) object with API that allows the generation of the filter state in the report

Value

(TealReportCard) populated with a title, description and filter state.


Create a teal module for previewing a report

Description

[Experimental]

This function wraps teal.reporter::reporter_previewer_ui() and teal.reporter::reporter_previewer_srv() into a teal_module to be used in teal applications.

If you are creating a teal application using init() then this module will be added to your application automatically if any of your teal_modules support report generation.

Usage

reporter_previewer_module(label = "Report previewer", server_args = list())

Arguments

label

(character(1)) Label shown in the navigation item for the module or module group. For modules() defaults to "root". See Details.

server_args

(named list) Arguments passed to teal.reporter::reporter_previewer_srv().

Value

teal_module (extended with teal_module_previewer class) containing the teal.reporter previewer functionality.


Restore value from bookmark.

Description

Get value from bookmark or return default.

Usage

restoreValue(value, default)

Arguments

value

(character(1)) name of value to restore

default

fallback value

Details

Bookmarks can store not only inputs but also arbitrary values. These values are stored by onBookmark callbacks and restored by onBookmarked callbacks, and they are placed in the values environment in the session$restoreContext field. Using teal_data_module makes it impossible to run the callbacks because the app becomes ready before modules execute and callbacks are registered. In those cases the stored values can still be recovered from the session object directly.

Note that variable names in the values environment are prefixed with module name space names, therefore, when using this function in modules, value must be run through the name space function.

Value

In an application restored from a server-side bookmark, the variable specified by value from the values environment. Otherwise default.


Run JS file from ⁠/inst/js/⁠ package directory

Description

This is triggered from the server to execute on the client rather than triggered directly on the client. Unlike include_js_files which includes JavaScript functions, the run_js actually executes JavaScript functions.

Usage

run_js_files(files)

Arguments

files

(character) vector of filenames.

Details

system.file should not be used to access files in other packages, it does not work with devtools. Therefore, we redefine this method in each package as needed. Thus, we do not export this method.

Value

NULL, invisibly.


Show R code modal

Description

[Deprecated]

Use the shiny::showModal() function to show the R code inside.

Usage

show_rcode_modal(title = NULL, rcode, session = getDefaultReactiveDomain())

Arguments

title

(character(1)) Title of the modal, displayed in the first comment of the R code.

rcode

(character) vector with R code to show inside the modal.

session

(ShinySession) optional shiny session object, defaults to shiny::getDefaultReactiveDomain().

References

shiny::showModal()


Store and restore teal_slices object

Description

Functions that write a teal_slices object to a file in the JSON format, and also restore the object from disk.

Usage

slices_store(tss, file)

slices_restore(file)

Arguments

tss

(teal_slices) object to be stored.

file

(character(1)) file path where teal_slices object will be saved and restored. The file extension should be ".json".

Details

Date and date time objects are stored in the following formats:

This format is assumed during slices_restore. All POSIX*t objects in selected or choices fields of teal_slice objects are always printed in UTC timezone as well.

Value

slices_store returns NULL, invisibly.

slices_restore returns a teal_slices object restored from the file.

See Also

teal_slices()


Create a tdata object

Description

[Superseded]

Recent changes in teal cause modules to fail because modules expect a tdata object to be passed to the data argument but instead they receive a teal_data object, which is additionally wrapped in a reactive expression in the server functions. In order to easily adapt such modules without a proper refactor, use this function to downgrade the data argument.

Usage

new_tdata(...)

tdata2env(...)

get_code_tdata(...)

## S3 method for class 'tdata'
join_keys(...)

get_metadata(...)

as_tdata(...)

Arguments

...

ignored

Value

nothing


Data module for teal applications

Description

[Experimental]

Create a teal_data_module object and evaluate code on it with history tracking.

Usage

teal_data_module(ui, server, label = "data module", once = TRUE)

## S4 method for signature 'teal_data_module,character'
eval_code(object, code)

## S3 method for class 'teal_data_module'
within(data, expr, ...)

Arguments

ui

(⁠function(id)⁠) shiny module UI function; must only take id argument

server

(⁠function(id)⁠) shiny module server function; must only take id argument; must return reactive expression containing teal_data object

label

(character(1)) Label of the module.

once

(logical(1)) If TRUE, the data module will be shown only once and will disappear after successful data loading. App user will no longer be able to interact with this module anymore. If FALSE, the data module can be reused multiple times. App user will be able to interact and change the data output from the module multiple times.

object

(teal_data_module)

code

(character, language or expression) code to evaluate. It is possible to preserve original formatting of the code by providing a character or an expression being a result of parse(keep.source = TRUE).

data

(teal_data_module) object

expr

(expression) to evaluate. Must be inline code. See within()

...

See Details.

Details

teal_data_module creates a shiny module to interactively supply or modify data in a teal application. The module allows for running any code (creation and some modification) after the app starts or reloads. The body of the server function will be run in the app rather than in the global environment. This means it will be run every time the app starts, so use sparingly.

Pass this module instead of a teal_data object in a call to init(). Note that the server function must always return a teal_data object wrapped in a reactive expression.

See vignette vignette("data-as-shiny-module", package = "teal") for more details.

eval_code evaluates given code in the environment of the teal_data object created by the teal_data_module. The code is added to the ⁠@code⁠ slot of the teal_data.

within is a convenience function for evaluating inline code inside the environment of a teal_data_module. It accepts only inline expressions (both simple and compound) and allows for injecting values into expr through the ... argument: as name:value pairs are passed to ..., name in expr will be replaced with value.

Value

teal_data_module returns a list of class teal_data_module containing two elements, ui and server provided via arguments.

eval_code returns a teal_data_module object with a delayed evaluation of code when the module is run.

within returns a teal_data_module object with a delayed evaluation of expr when the module is run.

See Also

teal.data::teal_data, teal.code::qenv()

Examples

tdm <- teal_data_module(
  ui = function(id) {
    ns <- NS(id)
    actionButton(ns("submit"), label = "Load data")
  },
  server = function(id) {
    moduleServer(id, function(input, output, session) {
      eventReactive(input$submit, {
        data <- within(
          teal_data(),
          {
            dataset1 <- iris
            dataset2 <- mtcars
          }
        )

        data
      })
    })
  }
)

eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')")

within(tdm, dataset1 <- subset(dataset1, Species == "virginica"))

# use additional parameter for expression value substitution.
valid_species <- "versicolor"
within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species)

Create a FilteredData

Description

Create a FilteredData object from a teal_data object.

Usage

teal_data_to_filtered_data(x, datanames = names(x))

Arguments

x

(teal_data) object

datanames

(character) vector of data set names to include; must be subset of names(x)

Value

A FilteredData object.


teal_data utils

Description

In teal we need to recreate the teal_data object due to two operations:

Usage

.append_evaluated_code(data, code)

.append_modified_data(data, objects)

Arguments

data

(teal_data)

code

(character) code to append to the object's code slot.

objects

(list) objects to append to object's environment.

Details

Due to above recreation of teal_data object can't be done simply by using public teal.code and teal.data methods.

Value

modified teal_data


Add a Custom Server Logic to teal Application

Description

Adds a custom server function to the teal app. This function can define additional server logic.

Usage

teal_extend_server(x, custom_server, module_id = character(0))

Arguments

x

(teal_app) A teal_app object created using the init function.

custom_server

(⁠function(input, output, session)⁠ or ⁠function(id, ...)⁠) The custom server function or server module to set.

module_id

(character(1)) The ID of the module when a module server function is passed.


Replace UI Elements in teal UI objects

Description

Replace UI Elements in teal UI objects

Usage

modify_title(x, title = "teal app", favicon = NULL)

modify_header(x, element = tags$p())

modify_footer(x, element = tags$p())

Arguments

x

(teal_app) A teal_app object created using the init function.

title

(shiny.tag or character(1)) The new title to be used.

favicon

(character) The path for the icon for the title. The image/icon path can be remote or the static path accessible by shiny, like the ⁠www/⁠. If the favicon is NULL the teal logo will be used as the favicon.

element

Replacement UI element (shiny tag or HTML)

Examples in Shinylive

example-1

Open in Shinylive

example-2

Open in Shinylive

example-3

Open in Shinylive

Examples

app <- init(
  data = teal_data(IRIS = iris, MTCARS = mtcars),
  modules = modules(example_module())
) |>
  modify_title(title = "Custom title")

if (interactive()) {
  shinyApp(app$ui, app$server)
}
app <- init(
  data = teal_data(IRIS = iris),
  modules = modules(example_module())
) |>
  modify_header(element = tags$div(h3("Custom header")))

if (interactive()) {
  shinyApp(app$ui, app$server)
}
app <- init(
  data = teal_data(IRIS = iris),
  modules = modules(example_module())
) |>
  modify_footer(element = "Custom footer")

if (interactive()) {
  shinyApp(app$ui, app$server)
}

Create teal_module and teal_modules objects

Description

[Stable] Create a nested tab structure to embed modules in a teal application.

Usage

module(
  label = "module",
  server = function(id, data, ...) moduleServer(id, function(input, output, session)
    NULL),
  ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),
  filters,
  datanames = "all",
  server_args = NULL,
  ui_args = NULL,
  transformators = list()
)

modules(..., label = "root")

## S3 method for class 'teal_module'
format(
  x,
  is_last = FALSE,
  parent_prefix = "",
  what = c("datasets", "properties", "ui_args", "server_args", "decorators",
    "transformators"),
  ...
)

## S3 method for class 'teal_modules'
format(x, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...)

## S3 method for class 'teal_module'
print(x, ...)

## S3 method for class 'teal_modules'
print(x, ...)

Arguments

label

(character(1)) Label shown in the navigation item for the module or module group. For modules() defaults to "root". See Details.

server

(function) shiny module with following arguments:

  • id - teal will set proper shiny namespace for this module (see shiny::moduleServer()).

  • input, output, session - (optional; not recommended) When provided, then shiny::callModule() will be used to call a module. From shiny 1.5.0, the recommended way is to use shiny::moduleServer() instead which doesn't require these arguments.

  • data (optional) If the server function includes a data argument, it will receive a reactive expression containing the teal_data object.

  • datasets (optional) When provided, the module will be called with FilteredData object as the value of this argument. (See teal.slice::FilteredData).

  • reporter (optional) When provided, the module will be called with Reporter object as the value of this argument. (See teal.reporter::Reporter).

  • filter_panel_api (optional) When provided, the module will be called with FilterPanelAPI object as the value of this argument. (See teal.slice::FilterPanelAPI).

  • ... (optional) When provided, server_args elements will be passed to the module named argument or to the ....

ui

(function) shiny UI module function with following arguments:

  • id - teal will set proper shiny namespace for this module.

  • ... (optional) When provided, ui_args elements will be passed to the module named argument or to the ....

filters

(character) Deprecated. Use datanames instead.

datanames

(character) Names of the datasets relevant to the item. There are 2 reserved values that have specific behaviors:

  • The keyword "all" includes all datasets available in the data passed to the teal application.

  • NULL hides the sidebar panel completely.

  • If transformators are specified, their datanames are automatically added to this datanames argument.

server_args

(named list) with additional arguments passed on to the server function.

ui_args

(named list) with additional arguments passed on to the UI function.

transformators

(list of teal_transform_module) that will be applied to transform module's data input. To learn more check vignette("transform-input-data", package = "teal").

...
  • For modules(): (teal_module or teal_modules) Objects to wrap into a tab.

  • For format() and print(): Arguments passed to other methods.

x

(teal_module or teal_modules) Object to format/print.

is_last

(logical(1)) Whether this is the last item in its parent's children list. Affects the tree branch character used (L- vs |-)

parent_prefix

(character(1)) The prefix inherited from parent nodes, used to maintain the tree structure in nested levels

what

(character) Specifies which metadata to display. Possible values: "datasets", "properties", "ui_args", "server_args", "transformators"

is_root

(logical(1)) Whether this is the root node of the tree. Only used in format.teal_modules(). Determines whether to show "TEAL ROOT" header

Details

module() creates an instance of a teal_module that can be placed in a teal application. modules() shapes the structure of a the application by organizing teal_module within the navigation panel. It wraps teal_module and teal_modules objects in a teal_modules object, which results in a nested structure corresponding to the nested tabs in the final application.

Note that for modules() label comes after ..., so it must be passed as a named argument, otherwise it will be captured by ....

The labels "global_filters" and "Report previewer" are reserved because they are used by the mapping argument of teal_slices() and the report previewer module reporter_previewer_module(), respectively.

Value

module() returns an object of class teal_module.

modules() returns a teal_modules object which contains following fields:

Restricting datasets used by teal_module:

The datanames argument controls which datasets are used by the module's server. These datasets, passed via server's data argument, are the only ones shown in the module's tab.

When datanames is set to "all", all datasets in the data object are treated as relevant. However, this may include unnecessary datasets, such as:

Datasets which name is prefixed in teal_data by the dot (.) are not displayed in the teal application. Please see the "Hidden datasets" section in 'vignette("including-data-in-teal-applications").

datanames with transformators

When transformators are specified, their datanames are added to the module's datanames, which changes the behavior as follows:

Examples in Shinylive

example-1

Open in Shinylive

Examples

library(shiny)

module_1 <- module(
  label = "a module",
  server = function(id, data) {
    moduleServer(
      id,
      module = function(input, output, session) {
        output$data <- renderDataTable(data()[["iris"]])
      }
    )
  },
  ui = function(id) {
    ns <- NS(id)
    tagList(dataTableOutput(ns("data")))
  },
  datanames = "all"
)

module_2 <- module(
  label = "another module",
  server = function(id) {
    moduleServer(
      id,
      module = function(input, output, session) {
        output$text <- renderText("Another Module")
      }
    )
  },
  ui = function(id) {
    ns <- NS(id)
    tagList(textOutput(ns("text")))
  },
  datanames = NULL
)

modules <- modules(
  label = "modules",
  modules(
    label = "nested modules",
    module_1
  ),
  module_2
)

app <- init(
  data = teal_data(iris = iris),
  modules = modules
)

if (interactive()) {
  shinyApp(app$ui, app$server)
}
mod <- module(
  label = "My Custom Module",
  server = function(id, data, ...) {},
  ui = function(id, ...) {},
  datanames = c("ADSL", "ADTTE"),
  transformators = list(),
  ui_args = list(a = 1, b = "b"),
  server_args = list(x = 5, y = list(p = 1))
)
cat(format(mod))
custom_module <- function(
    label = "label", ui_args = NULL, server_args = NULL,
    datanames = "all", transformators = list(), bk = FALSE) {
  ans <- module(
    label,
    server = function(id, data, ...) {},
    ui = function(id, ...) {
    },
    datanames = datanames,
    transformators = transformators,
    ui_args = ui_args,
    server_args = server_args
  )
  attr(ans, "teal_bookmarkable") <- bk
  ans
}

dummy_transformator <- teal_transform_module(
  label = "Dummy Transform",
  ui = function(id) div("(does nothing)"),
  server = function(id, data) {
    moduleServer(id, function(input, output, session) data)
  }
)

plot_transformator <- teal_transform_module(
  label = "Plot Settings",
  ui = function(id) div("(does nothing)"),
  server = function(id, data) {
    moduleServer(id, function(input, output, session) data)
  }
)

static_decorator <- teal_transform_module(
  label = "Static decorator",
  server = function(id, data) {
    moduleServer(id, function(input, output, session) {
      reactive({
        req(data())
        within(data(), {
          plot <- plot +
            ggtitle("This is title") +
            xlab("x axis")
        })
      })
    })
  }
)

complete_modules <- modules(
  custom_module(
    label = "Data Overview",
    datanames = c("ADSL", "ADAE", "ADVS"),
    ui_args = list(
      view_type = "table",
      page_size = 10,
      filters = c("ARM", "SEX", "RACE"),
      decorators = list(static_decorator)
    ),
    server_args = list(
      cache = TRUE,
      debounce = 1000,
      decorators = list(static_decorator)
    ),
    transformators = list(dummy_transformator),
    bk = TRUE
  ),
  modules(
    label = "Nested 1",
    custom_module(
      label = "Interactive Plots",
      datanames = c("ADSL", "ADVS"),
      ui_args = list(
        plot_type = c("scatter", "box", "line"),
        height = 600,
        width = 800,
        color_scheme = "viridis"
      ),
      server_args = list(
        render_type = "svg",
        cache_plots = TRUE
      ),
      transformators = list(dummy_transformator, plot_transformator),
      bk = TRUE
    ),
    modules(
      label = "Nested 2",
      custom_module(
        label = "Summary Statistics",
        datanames = "ADSL",
        ui_args = list(
          stats = c("mean", "median", "sd", "range"),
          grouping = c("ARM", "SEX")
        )
      ),
      modules(
        label = "Labeled nested modules",
        custom_module(
          label = "Subgroup Analysis",
          datanames = c("ADSL", "ADAE"),
          ui_args = list(
            subgroups = c("AGE", "SEX", "RACE"),
            analysis_type = "stratified"
          ),
          bk = TRUE
        )
      ),
      modules(custom_module(label = "Subgroup Analysis in non-labled modules"))
    )
  ),
  custom_module("Non-nested module")
)

cat(format(complete_modules))
cat(format(complete_modules, what = c("ui_args", "server_args", "transformators")))
cat(format(complete_modules, what = c("decorators", "transformators")))

Filter settings for teal applications

Description

Specify initial filter states and filtering settings for a teal app.

Usage

teal_slices(
  ...,
  exclude_varnames = NULL,
  include_varnames = NULL,
  count_type = NULL,
  allow_add = TRUE,
  module_specific = FALSE,
  mapping,
  app_id = NULL
)

as.teal_slices(x)

## S3 method for class 'teal_slices'
c(...)

Arguments

...

any number of teal_slice objects.

include_varnames, exclude_varnames

(⁠named list⁠s of character) where list names match names of data sets and vector elements match variable names in respective data sets; specify which variables are allowed to be filtered; see Details.

count_type

[Experimental] This is a new feature. Do kindly share your opinions on teal.slice's GitHub repository.

(character(1)) string specifying how observations are tallied by these filter states. Possible options:

  • "none" (default) to have counts of single FilterState to show unfiltered number only.

  • "all" to have counts of single FilterState to show number of observation in filtered and unfiltered dataset. Note, that issues were reported when using this option with MultiAssayExperiment. Please make sure that adding new filters doesn't fail on target platform before deploying for production.

allow_add

(logical(1)) logical flag specifying whether the user will be able to add new filters

module_specific

(logical(1)) optional,

  • FALSE (default) when one filter panel applied to all modules. All filters will be shared by all modules.

  • TRUE when filter panel module-specific. Modules can have different set of filters specified - see mapping argument.

mapping

[Experimental] This is a new feature. Do kindly share your opinions on teal's GitHub repository.

(named list) specifies which filters will be active in which modules on app start. Elements should contain character vector of teal_slice ids (see teal.slice::teal_slice). Names of the list should correspond to teal_module label set in module() function.

  • ids listed under ⁠"global_filters⁠ will be active in all modules.

  • If missing, all filters will be applied to all modules.

  • If empty list, all filters will be available to all modules but will start inactive.

  • If module_specific is FALSE, only global_filters will be active on start.

app_id

(character(1)) For internal use only, do not set manually. Added by init so that a teal_slices can be matched to the app in which it was used. Used for verifying snapshots uploaded from file. See snapshot.

x

(list) of lists to convert to teal_slices

Details

Produces a teal_slices object. The teal_slice components will specify filter states that will be active when the app starts. Attributes (created with the named arguments) will configure the way the app applies filters. See argument descriptions for details.

Value

A teal_slices object.

Examples in Shinylive

example-1

Open in Shinylive

See Also

teal.slice::teal_slices, teal.slice::teal_slice, slices_store()

Examples

filter <- teal_slices(
  teal_slice(dataname = "iris", varname = "Species", id = "species"),
  teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),
  teal_slice(
    dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"
  ),
  teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),
  mapping = list(
    module1 = c("species", "sepal_length"),
    module2 = c("mtcars_mpg"),
    global_filters = "long_petals"
  )
)

app <- init(
  data = teal_data(iris = iris, mtcars = mtcars),
  modules = list(
    module("module1"),
    module("module2")
  ),
  filter = filter
)

if (interactive()) {
  shinyApp(app$ui, app$server)
}


Data module for teal transformations and output customization

Description

[Experimental]

teal_transform_module provides a shiny module that enables data transformations within a teal application and allows for customization of outputs generated by modules.

Usage

teal_transform_module(
  ui = NULL,
  server = function(id, data) data,
  label = "transform module",
  datanames = "all"
)

Arguments

ui

(⁠function(id)⁠) shiny module UI function; must only take id argument

server

(⁠function(id, data)⁠ or expression) A shiny module server function that takes id and data as arguments, where id is the module id and data is the reactive teal_data input. The server function must return a reactive expression containing a teal_data object. For simplified syntax, use make_teal_transform_server().

label

(character(1)) Label of the module.

datanames

(character) Specifies the names of datasets relevant to the module. Only filters for the specified datanames will be displayed in the filter panel. The keyword "all" can be used to display filters for all datasets. datanames are automatically appended to the modules() datanames.

Transforming Module Inputs in teal

Data transformations occur after data has been filtered in teal. The transformed data is then passed to the server of teal_module() and managed by teal's internal processes. The primary advantage of teal_transform_module over custom modules is in its error handling, where all warnings and errors are managed by teal, allowing developers to focus on transformation logic.

For more details, see the vignette: vignette("transform-input-data", package = "teal").

Customizing Module Outputs

teal_transform_module also allows developers to modify any object created within teal.data::teal_data. This means you can use it to customize not only datasets but also tables, listings, and graphs. Some teal_modules permit developers to inject custom shiny modules to enhance displayed outputs. To manage these decorators within your module, use ui_transform_teal_data() and srv_transform_teal_data(). (For further guidance on managing decorators, refer to ui_args and srv_args in the vignette documentation.)

See the vignette vignette("transform-module-output", package = "teal") for additional examples.

server as a language

The server function in teal_transform_module must return a reactive teal.data::teal_data object. For simple transformations without complex reactivity, the server function might look like this:s

function(id, data) {
  moduleServer(id, function(input, output, session) {
    reactive({
      within(
        data(),
        expr = x <- subset(x, col == level),
        level = input$level
      )
    })
  })
}

The example above can be simplified using make_teal_transform_server, where level is automatically matched to the corresponding input parameter:

make_teal_transform_server(expr = expression(x <- subset(x, col == level)))

Examples in Shinylive

example-1

Open in Shinylive

Examples

data_transformators <- list(
  teal_transform_module(
    label = "Static transformator for iris",
    datanames = "iris",
    server = function(id, data) {
      moduleServer(id, function(input, output, session) {
        reactive({
          within(data(), {
            iris <- head(iris, 5)
          })
        })
      })
    }
  ),
  teal_transform_module(
    label = "Interactive transformator for iris",
    datanames = "iris",
    ui = function(id) {
      ns <- NS(id)
      tags$div(
        numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1)
      )
    },
    server = function(id, data) {
      moduleServer(id, function(input, output, session) {
        reactive({
          within(data(),
            {
              iris <- iris[, 1:n_cols]
            },
            n_cols = input$n_cols
          )
        })
      })
    }
  )
)

output_decorator <- teal_transform_module(
  server = make_teal_transform_server(
    expression(
      object <- rev(object)
    )
  )
)

app <- init(
  data = teal_data(iris = iris),
  modules = example_module(
    transformators = data_transformators,
    decorators = list(output_decorator)
  )
)
if (interactive()) {
  shinyApp(app$ui, app$server)
}


Function for validating the title parameter of teal::init

Description

Checks if the input of the title from teal::init will create a valid title and favicon tag.

Usage

validate_app_title_tag(shiny_tag)

Arguments

shiny_tag

(shiny.tag) Object to validate for a valid title.


Validate that dataset has a minimum number of observations

Description

[Stable]

Usage

validate_has_data(
  x,
  min_nrow = NULL,
  complete = FALSE,
  allow_inf = TRUE,
  msg = NULL
)

Arguments

x

(data.frame)

min_nrow

(numeric(1)) Minimum allowed number of rows in x.

complete

(logical(1)) Flag specifying whether to check only complete cases. Defaults to FALSE.

allow_inf

(logical(1)) Flag specifying whether to allow infinite values. Defaults to TRUE.

msg

(character(1)) Additional message to display alongside the default message.

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

library(teal)
ui <- fluidPage(
  sliderInput("len", "Max Length of Sepal",
    min = 4.3, max = 7.9, value = 5
  ),
  plotOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlot({
    iris_df <- iris[iris$Sepal.Length <= input$len, ]
    validate_has_data(
      iris_df,
      min_nrow = 10,
      complete = FALSE,
      msg = "Please adjust Max Length of Sepal"
    )

    hist(iris_df$Sepal.Length, breaks = 5)
  })
}
if (interactive()) {
  shinyApp(ui, server)
}


Validates that vector has length greater than 0

Description

[Stable]

Usage

validate_has_elements(x, msg)

Arguments

x

vector

msg

message to display

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

data <- data.frame(
  id = c(1:10, 11:20, 1:10),
  strata = rep(c("A", "B"), each = 15)
)
ui <- fluidPage(
  selectInput("ref1", "Select strata1 to compare",
    choices = c("A", "B", "C"), selected = "A"
  ),
  selectInput("ref2", "Select strata2 to compare",
    choices = c("A", "B", "C"), selected = "B"
  ),
  verbatimTextOutput("arm_summary")
)

server <- function(input, output) {
  output$arm_summary <- renderText({
    sample_1 <- data$id[data$strata == input$ref1]
    sample_2 <- data$id[data$strata == input$ref2]

    validate_has_elements(sample_1, "No subjects in strata1.")
    validate_has_elements(sample_2, "No subjects in strata2.")

    paste0(
      "Number of samples in: strata1=", length(sample_1),
      " comparions strata2=", length(sample_2)
    )
  })
}
if (interactive()) {
  shinyApp(ui, server)
}

Validates that dataset contains specific variable

Description

[Stable]

Usage

validate_has_variable(data, varname, msg)

Arguments

data

(data.frame)

varname

(character(1)) name of variable to check for in data

msg

(character(1)) message to display if data does not include varname

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

data <- data.frame(
  one = rep("a", length.out = 20),
  two = rep(c("a", "b"), length.out = 20)
)
ui <- fluidPage(
  selectInput(
    "var",
    "Select variable",
    choices = c("one", "two", "three", "four"),
    selected = "one"
  ),
  verbatimTextOutput("summary")
)

server <- function(input, output) {
  output$summary <- renderText({
    validate_has_variable(data, input$var)
    paste0("Selected treatment variables: ", paste(input$var, collapse = ", "))
  })
}
if (interactive()) {
  shinyApp(ui, server)
}

Validates that vector includes all expected values

Description

[Stable]

Usage

validate_in(x, choices, msg)

Arguments

x

Vector of values to test.

choices

Vector to test against.

msg

(character(1)) Error message to display if some elements of x are not elements of choices.

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

ui <- fluidPage(
  selectInput(
    "species",
    "Select species",
    choices = c("setosa", "versicolor", "virginica", "unknown species"),
    selected = "setosa",
    multiple = FALSE
  ),
  verbatimTextOutput("summary")
)

server <- function(input, output) {
  output$summary <- renderPrint({
    validate_in(input$species, iris$Species, "Species does not exist.")
    nrow(iris[iris$Species == input$species, ])
  })
}
if (interactive()) {
  shinyApp(ui, server)
}


Send input validation messages to output

Description

Captures messages from InputValidator objects and collates them into one message passed to validate.

Usage

validate_inputs(..., header = "Some inputs require attention")

Arguments

...

either any number of InputValidator objects or an optionally named, possibly nested list of InputValidator objects, see Details

header

(character(1)) generic validation message; set to NULL to omit

Details

shiny::validate is used to withhold rendering of an output element until certain conditions are met and to print a validation message in place of the output element. shinyvalidate::InputValidator allows to validate input elements and to display specific messages in their respective input widgets. validate_inputs provides a hybrid solution. Given an InputValidator object, messages corresponding to inputs that fail validation are extracted and placed in one validation message that is passed to a validate/need call. This way the input validator messages are repeated in the output.

The ... argument accepts any number of InputValidator objects or a nested list of such objects. If validators are passed directly, all their messages are printed together under one (optional) header message specified by header. If a list is passed, messages are grouped by validator. The list's names are used as headers for their respective message groups. If neither of the nested list elements is named, a header message is taken from header.

Value

Returns NULL if the final validation call passes and a shiny.silent.error if it fails.

Examples in Shinylive

example-1

Open in Shinylive

See Also

shinyvalidate::InputValidator, shiny::validate

Examples


library(shiny)
library(shinyvalidate)

ui <- fluidPage(
  selectInput("method", "validation method", c("sequential", "combined", "grouped")),
  sidebarLayout(
    sidebarPanel(
      selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),
      selectInput("number", "select a number:", 1:6),
      tags$br(),
      selectInput("color", "select a color:",
        c("black", "indianred2", "springgreen2", "cornflowerblue"),
        multiple = TRUE
      ),
      sliderInput("size", "select point size:",
        min = 0.1, max = 4, value = 0.25
      )
    ),
    mainPanel(plotOutput("plot"))
  )
)

server <- function(input, output) {
  # set up input validation
  iv <- InputValidator$new()
  iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter"))
  iv$add_rule("number", function(x) {
    if (as.integer(x) %% 2L == 1L) "choose an even number"
  })
  iv$enable()
  # more input validation
  iv_par <- InputValidator$new()
  iv_par$add_rule("color", sv_required(message = "choose a color"))
  iv_par$add_rule("color", function(x) {
    if (length(x) > 1L) "choose only one color"
  })
  iv_par$add_rule(
    "size",
    sv_between(
      left = 0.5, right = 3,
      message_fmt = "choose a value between {left} and {right}"
    )
  )
  iv_par$enable()

  output$plot <- renderPlot({
    # validate output
    switch(input[["method"]],
      "sequential" = {
        validate_inputs(iv)
        validate_inputs(iv_par, header = "Set proper graphical parameters")
      },
      "combined" = validate_inputs(iv, iv_par),
      "grouped" = validate_inputs(list(
        "Some inputs require attention" = iv,
        "Set proper graphical parameters" = iv_par
      ))
    )

    plot(faithful$eruptions ~ faithful$waiting,
      las = 1, pch = 16,
      col = input[["color"]], cex = input[["size"]]
    )
  })
}

if (interactive()) {
  shinyApp(ui, server)
}


Validate that variables has expected number of levels

Description

[Stable]

Usage

validate_n_levels(x, min_levels = 1, max_levels = 12, var_name)

Arguments

x

variable name. If x is not a factor, the unique values are treated as levels.

min_levels

cutoff for minimum number of levels of x

max_levels

cutoff for maximum number of levels of x

var_name

name of variable being validated for use in validation message

Details

If the number of levels of x is less than min_levels or greater than max_levels the validation will fail. This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

data <- data.frame(
  one = rep("a", length.out = 20),
  two = rep(c("a", "b"), length.out = 20),
  three = rep(c("a", "b", "c"), length.out = 20),
  four = rep(c("a", "b", "c", "d"), length.out = 20),
  stringsAsFactors = TRUE
)
ui <- fluidPage(
  selectInput(
    "var",
    "Select variable",
    choices = c("one", "two", "three", "four"),
    selected = "one"
  ),
  verbatimTextOutput("summary")
)

server <- function(input, output) {
  output$summary <- renderText({
    validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var)
    paste0(
      "Levels of selected treatment variable: ",
      paste(levels(data[[input$var]]),
        collapse = ", "
      )
    )
  })
}
if (interactive()) {
  shinyApp(ui, server)
}

Validates no intersection between two vectors

Description

[Stable]

Usage

validate_no_intersection(x, y, msg)

Arguments

x

vector

y

vector

msg

(character(1)) message to display if x and y intersect

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

data <- data.frame(
  id = c(1:10, 11:20, 1:10),
  strata = rep(c("A", "B", "C"), each = 10)
)

ui <- fluidPage(
  selectInput("ref1", "Select strata1 to compare",
    choices = c("A", "B", "C"),
    selected = "A"
  ),
  selectInput("ref2", "Select strata2 to compare",
    choices = c("A", "B", "C"),
    selected = "B"
  ),
  verbatimTextOutput("summary")
)

server <- function(input, output) {
  output$summary <- renderText({
    sample_1 <- data$id[data$strata == input$ref1]
    sample_2 <- data$id[data$strata == input$ref2]

    validate_no_intersection(
      sample_1, sample_2,
      "subjects within strata1 and strata2 cannot overlap"
    )
    paste0(
      "Number of subject in: reference treatment=", length(sample_1),
      " comparions treatment=", length(sample_2)
    )
  })
}
if (interactive()) {
  shinyApp(ui, server)
}


Validate that dataset has unique rows for key variables

Description

[Stable]

Usage

validate_one_row_per_id(x, key = c("USUBJID", "STUDYID"))

Arguments

x

(data.frame)

key

(character) Vector of ID variables from x that identify unique records.

Details

This function is a wrapper for shiny::validate.

Examples in Shinylive

example-1

Open in Shinylive

Examples

iris$id <- rep(1:50, times = 3)
ui <- fluidPage(
  selectInput(
    inputId = "species",
    label = "Select species",
    choices = c("setosa", "versicolor", "virginica"),
    selected = "setosa",
    multiple = TRUE
  ),
  plotOutput("plot")
)
server <- function(input, output) {
  output$plot <- renderPlot({
    iris_f <- iris[iris$Species %in% input$species, ]
    validate_one_row_per_id(iris_f, key = c("id"))

    hist(iris_f$Sepal.Length, breaks = 5)
  })
}
if (interactive()) {
  shinyApp(ui, server)
}

mirror server hosted at Truenetwork, Russian Federation.