Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Exploratory Web Apps for Analyzing Clinical Trials Data
Version:1.1.0
Date:2025-11-17
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.8.0), teal.slice(≥ 0.7.0)
Imports:bsicons, bslib (≥ 0.8.0), 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.7.0), teal.logger (≥ 0.4.0), teal.reporter (≥ 0.5.0.9001),teal.widgets (≥ 0.5.0), tools, utils
Suggests: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, r-lib/mirai,r-lib/cli, r-lib/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.3
Collate:'TealAppDriver.R' 'after.R' 'checkmate.R' 'dummy_functions.R''include_css_js.R' 'modules.R' 'init.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_source_code.R' 'module_teal.R' 'module_teal_lockfile.R''module_teal_reporter.R' 'module_transform_data.R''module_validate_error.R' 'reporter_previewer_module.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_slices-store.R' 'teal_slices.R''teal_transform_module.R' 'utils.R' 'validate_inputs.R''validations.R' 'zzz.R'
NeedsCompilation:no
Packaged:2025-11-17 11:36:39 UTC; sanchosl
Author:Dawid KaledkowskiORCID iD [aut, cre], Pawel Rucki [aut], Aleksander ChlebowskiORCID iD [aut], Andre VerissimoORCID iD [aut], Kartikeya Kirar [aut], Vedha Viyash [aut], Marcin Kosinski [aut], Adrian Waddell [aut], Dony Unardi [rev], Nina Qi [rev], Nikolas Burkoff [aut], Mahmoud Hallal [aut], Maciej Nasinski [aut], Konrad Pagacz [aut], Junlue Zhao [aut], Tadeusz Lewandowski [aut], Chendi Liao [rev], F. Hoffmann-La Roche AG [cph, fnd], Maximilian Mordig [ctb]
Maintainer:Dawid Kaledkowski <dawid.kaledkowski@roche.com>
Repository:CRAN
Date/Publication:2025-11-17 12:40:02 UTC

teal: Interactive exploration of clinical trials data

Description

Theteal package provides ashiny based framework for creating aninteractive data analysis environment.

Details

To learn mode about the package, visit theproject websiteor read theinit() manual page.

Author(s)

Maintainer: Dawid Kaledkowskidawid.kaledkowski@roche.com (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Adds signature protection to thedatanames in the data

Description

Adds signature protection to thedatanames in the data

Usage

.add_signature_to_data(data)

Arguments

data

(teal_data)

Value

teal_data with additional code that has signature of thedatanames


Calls expression when condition is met

Description

Function postponeshandlerExpr to the moment wheneventExpr (condition) returnsTRUE,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 expressionlike dataset(), or even a complex expression inside curly braces.

handlerExpr

The expression to call whenevereventExpr isinvalidated. This should be a side-effect-producing action (the returnvalue will be ignored). It will be executed within anisolate()scope.

event.env

The parent environment for the reactive expression. By default,this is the calling environment, the same as when defining an ordinarynon-reactive expression. IfeventExpr is a quosure andevent.quoted isTRUE,thenevent.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 ordinarynon-reactive expression. IfhandlerExpr is a quosure andhandler.quoted isTRUE,thenhandler.env is ignored.

...

additional arguments passed toobserveEvent with the exception ofeventExpr 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 ofdatasets

Value

A character vector with the code lines.


Temporary function to handle server_args of the report_previewer_module before its harddeprecation.

Description

Temporary function to handle server_args of the report_previewer_module before its harddeprecation.

Usage

.get_reporter_options(args)

Arguments

args

(list)


Smartrbind

Description

Combinedata.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 classcharacter of length 1.


Drive ateal application

Description

Drive ateal application

Drive ateal application

Details

Extension of theshinytest2::AppDriver class with methods fordriving a teal application for performing interactions forshinytest2 tests.

Super class

shinytest2::AppDriver ->TealAppDriver

Methods

Public methods

Inherited methods

Methodnew()

Initialize aTealAppDriver object for testing ateal application.

Usage
TealAppDriver$new(  app,  options = list(),  timeout = rlang::missing_arg(),  load_timeout = rlang::missing_arg(),  ...)
Arguments
app

(teal_app)

options

(list) passed toshinyApp(options). Seeshiny::shinyApp().

timeout

(numeric) Default number of milliseconds for any timeout ortimeout_ parameter in theTealAppDriver class.Defaults to 20s.

Seeshinytest2::AppDrivernew method for more details on how to change itvia 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.

Seeshinytest2::AppDrivernew method for more details on how to change itvia options or environment variables

...

Additional arguments to be passed toshinytest2::AppDriver$new

Returns

Object of classTealAppDriver


Methodclick()

Append parentshinytest2::AppDriverclick method with a call towaif_for_idle() method.

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

arguments passed to parentshinytest2::AppDriverclick() method.


Methodexpect_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 tabis 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()

Methodexpect_no_validation_error()

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

Usage
TealAppDriver$expect_no_validation_error()

Methodexpect_validation_error()

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

Usage
TealAppDriver$expect_validation_error()

Methodset_input()

Set the input in theteal 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 toshinytest2::AppDriver$set_inputs

Returns

TheTealAppDriver object invisibly.


Methodnavigate_teal_tab()

Navigate the teal tabs in theteal app.

Usage
TealAppDriver$navigate_teal_tab(tab)
Arguments
tab

(character) Labels of tabs to navigate to.Note: Make sure to provide unique labels for the tabs.

Returns

TheTealAppDriver object invisibly.


Methodnamespaces()

NS in different sections ofteal app

Usage
TealAppDriver$namespaces(is_selector = FALSE)
Arguments
is_selector

(logical(1)) whetherns function should prefix with⁠#⁠.

Returns

list ofns.


Methodget_active_module_input()

Get the input from the module in theteal 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.


Methodget_active_module_output()

Get the output from the module in theteal 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.


Methodget_active_module_table_output()

Get the output from the module'steal.widgets::table_with_settings orDT::DTOutput in theteal 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 usingteal.widgets::table_with_settings.

Returns

The data.frame with table contents.


Methodget_active_module_plot_output()

Get the output from the module'steal.widgets::plot_with_settings in theteal 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

Thesrc attribute ascharacter(1) vector.


Methodset_active_module_input()

Set the input in the module in theteal 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 toshinytest2::AppDriver$set_inputs

Returns

TheTealAppDriver object invisibly.


Methodget_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()

Methodget_active_data_summary_table()

Get the active data summary table

Usage
TealAppDriver$get_active_data_summary_table()
Returns

data.frame


Methodis_visible()

Test ifDOM 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.ACSS id will return only one element if the UI is well formed.

content_visibility_auto, opacity_property, visibility_property

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

Returns

Logical vector with all occurrences of the selector.


Methodget_active_data_filters()

Get the active filter variables from a dataset in theteal 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.IfNULL, the filter variables for all the datasets will be returned in a list.


Methodadd_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 toshinytest2::AppDriver$set_inputs

Returns

TheTealAppDriver object invisibly.


Methodremove_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.IfNULL, all the filter variables will be removed.

var_name

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

Returns

TheTealAppDriver object invisibly.


Methodset_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 toshinytest2::AppDriver$set_inputs

Returns

TheTealAppDriver object invisibly.


Methodget_attr()

Extracthtml attribute (found by aselector).

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 byselector.

Returns

Thecharacter vector.


Methodget_html_rvest()

Wrapper aroundget_html that passes the output directly torvest::read_html.

Usage
TealAppDriver$get_html_rvest(selector)
Arguments
selector

(character(1)) passed toget_html.

Returns

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


Methodopen_url()

Usage
TealAppDriver$open_url()
Returns

Nothing. Opens the underlying teal app in the browser.


Methodwait_for_active_module_value()

Waits until a specified input, output, or export value.This function serves as a wrapper around thewait_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 inwait_for_value.


TealReportCard

Description

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

Super class

teal.reporter::ReportCard ->TealReportCard

Methods

Public methods

Inherited methods

Methodappend_src()

Appends the source code to thecontent meta data of thisTealReportCard.

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

(character(1)) code as text.

...

anyrmarkdownR chunk parameter and its value.Buteval parameter is always set toFALSE.

Returns

Object of classTealReportCard, invisibly.

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

Methodappend_fs()

Appends the filter state list to thecontent andmetadata of thisTealReportCard.If the filter state list has an attribute namedformatted, it appends it to the card otherwise it usesthe defaultyaml::as.yaml to format the list.If the filter state list is empty, nothing is appended to thecontent.

Usage
TealReportCard$append_fs(fs)
Arguments
fs

(teal_slices) object returned fromteal_slices() function.

Returns

self, invisibly.


Methodappend_encodings()

Appends the encodings list to thecontent andmetadata of thisTealReportCard.

Usage
TealReportCard$append_encodings(encodings)
Arguments
encodings

(list) list of encodings selections of theteal app.

Returns

self, invisibly.

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

Methodclone()

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]]## ------------------------------------------------## Method `TealReportCard$append_encodings`## ------------------------------------------------card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))card$get_content()[[1]]

Add a Landing Popup toteal Application

Description

Adds a landing popup to theteal 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) Ateal_app object created using theinit function.

title

An optional title for the dialog.

content

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

footer

UI for footer. UseNULL for no footer.

...

Additional arguments toshiny::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)}

Executes modifications to the result of a module

Description

[Experimental]

Exported to be able to use methods not to be used directly by module-developers or app-users.Primarily used to modify the output object of module.

Usage

after(x, server = function(input, output, session, data) data, ...)

Arguments

x

(teal_module orteal_modules).

server

(⁠function(input, output, session, data, ...)⁠) function to receive output data fromtm$server.Must return data

...

Additional arguments passed to the server wrapper function by matching their formal names.

Value

Ateal_module orteal_modules object with a wrapped server.

See Also

disable_src(),disable_report()

Examples

library("teal.reporter")hide_code <- function(input, output, session, data) {  teal_card(data) <- Filter(function(x) !inherits(x, "code_chunk"), teal_card(data))  data}app <- init(  data = teal_data(IRIS = iris, MTCARS = mtcars),  modules = example_module() |>    after(server = hide_code))if (interactive()) {  runApp(app)}

Append ateal_module tochildren of ateal_modules object

Description

Append ateal_module tochildren of ateal_modules object

Usage

append_module(modules, module)

Arguments

modules

(teal_modules)

module

(teal_module) object to be appended onto the children ofmodules

Value

Ateal_modules object withmodule appended.


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 theteal app.

favicon

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

Value

Ashiny.tag containing the element that adds the title and logo to theshiny app.


Checkdatanames in filters

Description

This function checks whetherdatanames in filters correspond to those indata,returning character vector with error messages orTRUE if all checks pass.

Usage

check_filter_datanames(filters, datanames)

Arguments

filters

(teal_slices) object

datanames

(character) names of datasets available in thedata object

Value

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


Checkdatanames in modules

Description

These functions check if specifieddatanames in modules match those in the data object,returning error messages orTRUE for successful validation. Two functions return error messagein 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 thedata object

Value

TRUE if validation passes, otherwisecharacter(1) orshiny.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 toTRUE,x may also beNULL.In this case only a type check ofx is performed, all additional checks are disabled.

.var.name

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

add

[AssertCollection]
Collection to store assertion messages. SeeAssertCollection.

Value

Depending on the function prefix:If the check is successful, the functionsassertClass/assert_class returnx invisibly, whereascheckClass/check_class andtestClass/test_class returnTRUE.If the check is not successful,assertClass/assert_classthrows an error message,testClass/test_classreturnsFALSE,andcheckClass/check_class return a string with the error message.The functionexpect_class always returns anexpectation.


Application ID

Description

Creates App ID used to match filter snapshots to application.

Usage

create_app_id(data, modules)

Arguments

data

(teal_data orteal_data_module) as accepted byinit

modules

(teal_modules) object as accepted byinit

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 copyteal_slices

Description

it's important to create a new copy ofteal_slices whenstarting a newshiny session. Otherwise, object will be sharedby multiple users as it is created in global environment beforeshiny session starts.

Usage

deep_copy_filter(filter)

Arguments

filter

(teal_slices)

Value

teal_slices


Disable the report for ateal_module

Description

Convenience function that disables the user's ability to add the moduleto the report previewer.

Usage

disable_report(x)

Arguments

x

(teal_module) ateal_module object.

Value

modified data object that indicates that it should disable the reporter functionality.

Examples in Shinylive

example-1

Open in Shinylive

example-2

Open in Shinylive

example-3

Open in Shinylive

See Also

disable_src()

Examples

# Disabling report on a single moduleapp <- init(  data = within(teal_data(), iris <- iris),  modules = modules(    example_module(label = "example teal module") |> disable_report()  ))if (interactive()) {  shinyApp(app$ui, app$server)}# Disabling report on multiple modulesapp <- init(  data = within(teal_data(), iris <- iris),  modules = modules(    example_module(label = "example 1"),    example_module(label = "example 2")  ) |> disable_report())if (interactive()) {  shinyApp(app$ui, app$server)}# Disabling reporting for the appapp <- init(  data = within(teal_data(), iris <- iris),  modules = modules(    example_module(label = "example teal module")  ),  reporter = NULL)if (interactive()) {  shinyApp(app$ui, app$server)}

Disable the "Show R Code" global button in the UI

Description

Convenience function that disables the user's ability to see the code of the module.

Usage

disable_src(x)

Arguments

x

(teal_module) ateal_module object.

Details

This is equivalent to setting the attributeteal.enable_src toFALSE on thedata object returned by the module.

Value

modified data object that indicates that it should not show the "Show R Code"button in the UI.

Examples in Shinylive

example-1

Open in Shinylive

example-2

Open in Shinylive

See Also

disable_report()

Examples

# Disabling source on a single moduleapp <- init(  data = within(teal_data(), iris <- iris),  modules = modules(    example_module(label = "example teal module") |> disable_src()  ))if (interactive()) {  shinyApp(app$ui, app$server)}# Multiple modulesapp <- init(  data = within(teal_data(), iris <- iris),  modules = modules(    example_module(label = "example 1"),    example_module(label = "example 2")  ) |> disable_src())if (interactive()) {  shinyApp(app$ui, app$server)}

An exampleteal module

Description

This module creates an object calledobject that can be modified with decorators.Theobject is determined by what's selected in⁠Choose a dataset⁠ input in UI.The object can be anything that can be handled byrenderPrint().See thevignette("transform-module-output", package = "teal") orteal_transform_moduleto read more about decorators.

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.Formodules() defaults to"root". SeeDetails.

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.

  • Iftransformators are specified, theirdatanames are automatically added to thisdatanamesargument.

transformators

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

decorators

[Experimental] (list ofteal_transform_module) optional,decorator forobject included in the module.

Value

Ateal module which can be included in themodules argument toinit().

Reporting

This module returns an object of classteal_module, that contains aserver function.Since the server function returns ateal_report object, this makes this module reportable, which means thatthe reporting functionality will be turned on automatically by theteal framework.

For more information on reporting inteal, see the vignettes:

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 ateal_module or ateal_modules, return the elements of the structure according toclass.

Usage

extract_module(modules, class)drop_module(modules, class)

Arguments

modules

(teal_modules)

class

The class name ofteal_module to be extracted or dropped.

Value

teal_modules


Extract alltransformators frommodules.

Description

Extract alltransformators frommodules.

Usage

extract_transformators(modules)

Arguments

modules

teal_modules orteal_module

Value

A list ofteal_transform_module nested in the same way as inputmodules.


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 ashiny input which contains information about the timezone in the browser.

Usage

get_client_timezone(ns)

Arguments

ns

(function) namespace function passed from thesession object in theshiny server.Forshiny 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


IncludeCSS files from⁠/inst/css/⁠ package directory to application header

Description

system.file should not be used to access files in other packages, it doesnot work withdevtools. Therefore, we redefine this method in each packageas 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 includesCSS files.


Code to includetealCSS andJavaScript files

Description

This is useful when you want to use the sameJavaScript andCSS files that areused with theteal application.This is also useful for running standalone modules inteal with the correctstyles.Also initializesshinyjs so you can use it.

Usage

include_teal_css_js()

Details

Simply addinclude_teal_css_js() as one of the UI elements.

Value

Ashiny.tag.list.


Create the server and UI function for theshiny app

Description

End-users: This is the most important function for you to start ateal app that is composed ofteal modules.

Usage

init(  data,  modules,  filter = teal_slices(),  title = lifecycle::deprecated(),  header = lifecycle::deprecated(),  footer = lifecycle::deprecated(),  id = lifecycle::deprecated(),  reporter = teal.reporter::Reporter$new())

Arguments

data

(teal_data orteal_data_module)For constructing the data object, refer toteal.data::teal_data() andteal_data_module().

modules

(list orteal_modules orteal_module)Nested list ofteal_modules orteal_module objects or a singleteal_modules orteal_module object. These are the specific output modules whichwill be displayed in theteal application. Seemodules() andmodule() formore details.

filter

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

title

(shiny.tag orcharacter(1))[Deprecated] Optionally,the browser window title. Defaults to a title "teal app" with the icon of NEST.Can be created using thebuild_app_title() orby passing a validshiny.tag which is a head tag with title and link tag.This parameter is no longer supported. Usemodify_title() on the teal app object instead.

header

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

footer

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

id

[Deprecated] (character) Optionally,a string specifying theshiny module id in cases it is used as ashiny modulerather than a standaloneshiny app.This parameter is no longer supported. Useui_teal() andsrv_teal() instead.

reporter

(Reporter) object used to store report contents. Set toNULL to globally disable reporting.

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 thearg

Description

Does the object make use of thearg

Usage

is_arg_used(modules, arg)

Arguments

modules

(teal_module orteal_modules) object

arg

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

Value

logical whether the object makes use ofarg.


Make teal_transform_module's server

Description

A factory function to simplify creation of ateal_transform_module's server. Specifiedexpris wrapped in a shiny module function and output can be passed to theserver argument inteal_transform_module() call. Such a server function can be linked with ui and values from theinputs can be used in the expression. Object names specified in the expression will be substitutedwith the value of the respective input (matched by the name) - for example inexpression(graph <- graph + ggtitle(title)) objecttitle will be replaced with the value ofinput$title.

Usage

make_teal_transform_server(expr)

Arguments

expr

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

Value

⁠function(id, data)⁠ returningshiny 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 whichwill be displayed in theteal application. Seemodules() andmodule() formore details.

Details

This module introduces bookmarks intoteal apps: theshiny bookmarking mechanism becomes enabledand 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 ateal_bookmarkable attribute set toTRUE. 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 developershould set theteal_bookmarkable attribute toTRUE.

Value

InvisibleNULL.

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 returningteal_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 tablecontaining datasets where number of observations are not calculated.

Value

NULL.


Filter panel module in teal

Description

Creates filter panel module fromteal_data object and returnsteal_data. It is build in a waythat filter panel changes and anything what happens before (e.g.module_init_data) is triggeringfurther reactive events only if something has changed and if the module is visible. Thanks tothis special implementation all modules' data are recalculated only for those modules which arecurrently 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 returningFilteredData orNULL)Whendatasets is passed from the parent module (srv_teal) thendataset is a singletonwhich implies the filter-panel to be "global". WhenNULL then filter-panel is "module-specific".

active_datanames

(reactive returningcharacter) this module's data names

data

(reactive returningteal_data)

modules

(teal_modules)teal_modules object. These are the specific output modules whichwill be displayed in theteal application. Seemodules() andmodule() formore details.

Value

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


Manage multipleFilteredData 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)containingteal_slices.

module_fd

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

Value

Module returns aslices_global (reactiveVal) containing ateal_slices object with mapping.

Slices global

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

During a session only new filters are added toall_slices unlessmodule_snapshot_manager isused to restore previous state. Filters fromall_slices can be activated or deactivated in amodule which is linked (both ways) byattr(, "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 inthe filters inslices_global and displays them in a table utilizing information frommapping:

  1. ui/srv_module_filter_manager - Called once for eachteal_module. Handling filter statesfor of single module and keeping moduleFilteredData consistent withslices_global, so thatlocal filters are always reflected in theslices_global and its mapping and vice versa.


Data Module for teal

Description

This module manages thedata argument forsrv_teal. Theteal framework usesteal.data::teal_data(),which can be provided in various ways:

  1. Directly as ateal.data::teal_data() object. This will automatically convert it into areactiveteal_data.

  2. As areactive object that returns ateal.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, orreactive returningteal_data)The data which application will depend on.

Details

Reactiveteal_data:

The data in the application can be reactively updated, promptingsrv_teal() to rebuild thecontent accordingly. There are two methods for creating interactiveteal_data:

  1. Using areactive object provided from outside theteal application. In this scenario,reactivity is controlled by an external module, andsrv_teal responds to changes.

  2. Usingteal_data_module(), which is embedded within theteal application, allowing data tobe resubmitted by the user as needed.

Since the server ofteal_data_module() must return areactiveteal_data object, bothmethods (1 and 2) produce the same reactive behavior within ateal application. The distinctionlies in data control: the first method involves external control, while the second methodinvolves control from a custom module within the app.

Value

Areactive object that returns:Output of thedata. Ifdata fails then returned error is handled (aftertryCatch()) so thatrest of the application can respond to this respectively.


teal user session info module

Description

Module to display the user session info popup and to download a lockfile. Module is includedwhen runninginit() but skipped when usingmodule_teal. Please be aware that session infocontains 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 ateal_slices objectcontaining allteal_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 fileand 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 unlistedteal_slices object.

Server logic

Snapshots are basicallyteal_slices objects, however, since each module is served by a separate instanceofFilteredData and these objects require shared state,teal_slice is areactiveVal soteal_slicescannot be stored as is. Therefore,teal_slices are reversibly converted to a list of lists representation(attributes are maintained).

Snapshots are stored in areactiveVal 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 containsthe 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 fromslices_global andmapping_matrix.The former provides a list of all existingteal_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 themapping attribute of the initial application state(or one that has been restored), which may not reflect the current one,somapping_matrix is transformed to obtain the current mapping, i.e. a list that,when passed to themapping argument ofteal_slices(), would result in the current mapping.This is substituted as the snapshot'smapping attribute and the snapshot is added to the snapshot list.

To restore app state, a snapshot is retrieved from storage and rebuilt into ateal_slices object.Then state of allFilteredData objects (provided indatasets) is clearedand set anew according to themapping attribute of the snapshot.The snapshot is then set as the current content ofslices_global.

To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,and then saved to file withslices_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 uploadand 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 ateal_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 stampsteal_slices with an app id that is stored in theapp_id attribute ofateal_slices object. When a snapshot is restored from file, itsapp_id is compared to thatof the current app state and only if the match is the snapshot admitted to the session.

Bookmarks

AnonBookmark 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 bymodule_teal in order to set initial app state in a restored app.)Then that snapshot, and the previous snapshot history are dumped into thevalues.rds file in⁠<bookmark_dir>⁠.

Author(s)

Aleksander Chlebowski


teal main module

Description

Module to create ateal app as a Shiny Module.

Usage

ui_teal(id, modules)srv_teal(  id,  data,  modules,  filter = teal_slices(),  reporter = teal.reporter::Reporter$new())

Arguments

id

(character(1))shiny module instance id.

modules

(teal_modules)teal_modules object. These are the specific output modules whichwill be displayed in theteal application. Seemodules() andmodule() formore details.

data

(teal_data,teal_data_module, orreactive returningteal_data)The data which application will depend on.

filter

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

reporter

(Reporter) object used to store report contents. Set toNULL to globally disable reporting.

Details

This module can be used instead ofinit() in custom Shiny applications. Unlikeinit(), it doesn'tautomatically includemodule_session_info.

Module is responsible for creating the mainshiny app layout and initializing all the necessarycomponents. This module establishes reactive connection between the inputdata and every othercomponent in the app. Reactive change of thedata passed as an argument, reloads the app andpossibly keeps all input settings the same so the user can continue where one left off.

data flow inteal application

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

Fallback on failure

teal is designed in such way that app will never crash if the error is introduced in anycustomshiny 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


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 leveragesrenv::snapshot(), which offers multiple methods for lockfile creation.

lockfile usage

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

See Also

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


Calls allmodules

Description

Modules create navigation bar with drop-down menu and tab content. Eachteal_module is called recursivelyaccording to the structure ofmodules argument. This is a custom module which utilizes shiny/Bootstrap.nav class.modules are called with anid derived fromteal_module's label and labels of itsancestors (if any).

Usage

ui_teal_module(id, modules)srv_teal_module(  id,  data,  modules,  datasets = NULL,  slices_global,  reporter = teal.reporter::Reporter$new(),  data_load_status = reactive("ok")).teal_navbar_append(navbar, child).teal_navbar_insert_ui(  ui,  where = "afterBegin",  session = getDefaultReactiveDomain()).teal_navbar_menu(..., id = NULL, label = NULL, class = NULL, icon = NULL).ui_teal_module(id, modules, active_module_id)## Default S3 method:.ui_teal_module(id, modules, active_module_id)## S3 method for class 'teal_modules'.ui_teal_module(id, modules, active_module_id)## S3 method for class 'teal_module'.ui_teal_module(id, modules, active_module_id).srv_teal_module(  id,  data,  modules,  datasets = NULL,  slices_global,  reporter = teal.reporter::Reporter$new(),  data_load_status = reactive("ok"),  active_module_id = 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"),  active_module_id = 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"),  active_module_id = 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"),  active_module_id = reactive(TRUE))

Arguments

id

(character(1))shiny module instance id.

modules

(teal_modules)teal_modules object. These are the specific output modules whichwill be displayed in theteal application. Seemodules() andmodule() formore details.

data

(reactive returningteal_data)

datasets

(reactive returningFilteredData orNULL)Whendatasets is passed from the parent module (srv_teal) thendataset is a singletonwhich implies the filter-panel to be "global". WhenNULL then filter-panel is "module-specific".

slices_global

(reactiveVal returningmodules_teal_slices)seemodule_filter_manager

reporter

(Reporter, singleton)Stores reporter-cards appended in the server ofteal_module.

data_load_status

(reactive returningcharacter(1))Determines action dependent on a data loading status:

  • "ok" whenteal_data is returned from the data loading.

  • "teal_data_module failed" whenteal_data_module() didn't returnteal_data. Disables tab buttons.

  • "external failed" when areactive passed tosrv_teal(data) didn't returnteal_data. Hides the whole tabpanel.

active_module_id

(reactive returningcharacter(1))id of the currently active module. This helps to determine which module can listen to reactive events.

Details

Functions

Utilizing.nav class

No extrajavascript or server functionality were introduced to have navigation buttons toggle betweentab panels. This works thanks to.nav container which links.nav-link buttons⁠href = #<module id>⁠attribute with.tab-pane's⁠id = <module id>⁠ (see “.ui_teal_module.teal_module').

Initialization and isolation of theteal_module(s)

Modules are initialized only when they are active. This speeds up app initialization and onstartup only the first module is activated and its outputs are calculated.Only the active module is listening to reactive events. This way, modules are isolated and onlyone can run at any given time. This makes the app more efficient by reducing unnecessarycomputations on server side.

Value

Output of currently active module.


Module to transformreactiveteal_data

Description

Module callsteal_transform_module() in sequence so that⁠reactive teal_data⁠ outputfrom 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 ofteal_transform_module) that will be applied to transform module's data input.To learn more checkvignette("transform-input-data", package = "teal").

class

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

data

(teal_data,teal_data_module, orreactive returningteal_data)The data which application will depend on.

modules

(teal_modules orteal_module) Fordatanames validation purpose

is_transform_failed

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

Value

reactiveteal_data


Execute and validateteal_data_module

Description

This is a low level module to handleteal_data_module execution and validation.teal_transform_module() inherits fromteal_data_module() so it is handled by this module too.srv_teal() accepts variousdata objects and eventually they are all transformed toreactiveteal.data::teal_data() which is a standard data class in wholeteal framework.

Usage

ui_validate_error(id)srv_validate_error(id, data, validate_shiny_silent_error)ui_check_class_teal_data(id)srv_check_class_teal_data(id, data)ui_check_module_datanames(id)srv_check_module_datanames(id, data, modules)

Arguments

id

(character(1))shiny module instance id.

data

(teal_data,teal_data_module, orreactive returningteal_data)The data which application will depend on.

validate_shiny_silent_error

(logical) IfTRUE, thenshiny.silent.error is validated and

modules

(teal_modules orteal_module) Fordatanames validation purpose

Value

reactiveteal_data

data validation

Executedteal_data_module() is validated and output is validated for consistency.Outputdata is invalid if:

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

  2. reactive throws ashiny.error - happens when module creatingteal.data::teal_data() fails.

  3. reactive returnsqenv.error - happens whenteal.data::teal_data() evaluates a failing code.

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

  5. teal.data::teal_data() object lacks anydatanames specified in themodules argument.

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


Retrieveteal_bookmarkable attribute fromteal_modules

Description

Retrieveteal_bookmarkable attribute fromteal_modules

Usage

modules_bookmarkable(modules)

Arguments

modules

(teal_modules orteal_module) object

Value

named list of the same structure asmodules withTRUE orFALSE values indicatingwhether the module is bookmarkable.


Retrieve slot fromteal_modules

Description

Retrieve slot fromteal_modules

Usage

modules_slot(modules, slot)

Arguments

modules

(teal_modules)

slot

(character(1))

Value

Alist containing theslot of the modules.If the modules are nested, the function returns a nestedlist of values.


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

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

Value

Acharacter that correctly represents the size of thex argument.


Template function forTealReportCard 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 generationof the filter state in the report

Value

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


Create ateal module for previewing a report

Description

[Deprecated]

This function controls the appearance of the drop-down menu for the reporter.It is now deprecated in favor of the options:

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.Formodules() defaults to"root". SeeDetails.

server_args

(namedlist) Arguments will overwrite the defaultteal.reporter optionsdescribed in the description.

Value

teal_module (extended withteal_module_previewer class) containing theteal.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 byonBookmark callbacks and restored byonBookmarked callbacks,and they are placed in thevalues environment in thesession$restoreContext field.Usingteal_data_module makes it impossible to run the callbacksbecause the app becomes ready before modules execute and callbacks are registered.In those cases the stored values can still be recovered from thesession object directly.

Note that variable names in thevalues 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 byvalue from thevalues environment.Otherwisedefault.


Store and restoreteal_slices object

Description

Functions that write ateal_slices object to a file in theJSON 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 whereteal_slices object will besaved and restored. The file extension should be".json".

Details

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

This format is assumed duringslices_restore. AllPOSIX*t objects inselected orchoices fields ofteal_slice objects are always printed inUTC timezone as well.

Value

slices_store returnsNULL, invisibly.

slices_restore returns ateal_slices object restored from the file.

See Also

teal_slices()


Data module forteal applications

Description

[Experimental]

Create ateal_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'eval_code(object, code)## S3 method for class 'teal_data_module'within(data, expr, ...)

Arguments

ui

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

server

(⁠function(id)⁠)shiny module server function; must only takeid argument;must return reactive expression containingteal_data object

label

(character(1)) Label of the module.

once

(logical(1))IfTRUE, 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.IfFALSE, 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 orexpression) code to evaluate.It is possible to preserve original formatting of thecode by providing acharacter or anexpression being a result ofparse(keep.source = TRUE).

data

(teal_data_module) object

expr

(expression) to evaluate. Must be inline code. Seewithin()

...

SeeDetails.

Details

teal_data_module creates ashiny module to interactively supply or modify data in ateal application.The module allows for running any code (creationand 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 ateal_data object in a call toinit().Note that the server function must always return ateal_data object wrapped in a reactive expression.

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

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

within is a convenience function for evaluating inline code inside the environment of ateal_data_module.It accepts only inline expressions (both simple and compound) and allows for injecting values intoexpr throughthe... argument: asname:value pairs are passed to...,name inexpr will be replaced withvalue.

Value

teal_data_module returns a list of classteal_data_module containing two elements,ui andserver provided via arguments.

eval_code returns ateal_data_module object with a delayed evaluation ofcode when the module is run.

within returns ateal_data_module object with a delayed evaluation ofexpr 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 aFilteredData

Description

Create aFilteredData object from ateal_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 ofnames(x)

Value

AFilteredData object.


teal_data utils

Description

Inteal we need to recreate theteal_data object due to two operations:

Usage

.append_evaluated_code(data, code, filter_states).append_modified_data(data, objects).collapse_subsequent_chunks(card)

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 ofteal_data object can't be done simply by using publicteal.code andteal.data methods.

Value

modifiedteal_data


Add a Custom Server Logic toteal Application

Description

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

Usage

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

Arguments

x

(teal_app) Ateal_app object created using theinit 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 inteal UI objects

Description

Replace UI Elements inteal 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) Ateal_app object created using theinit function.

title

(shiny.tag orcharacter(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 byshiny, like the⁠www/⁠.If the favicon isNULL theteal 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)}

Createteal_module andteal_modules objects

Description

Create a nested tab structure to embed modules in ateal 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 = character(0))## 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.Formodules() defaults to"root". SeeDetails.

server

(function)shiny module with following arguments:

  • id -teal will set propershiny namespace for this module (seeshiny::moduleServer()).

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

  • data (optional) If the server function includes adata argument, it will receive a reactiveexpression containing theteal_data object.

  • datasets (optional) When provided, the module will be called withFilteredData object as thevalue of this argument. (Seeteal.slice::FilteredData).

  • reporter (optional) When provided, the module will be called withReporter object as the valueof this argument. (Seeteal.reporter::Reporter).

  • filter_panel_api (optional) When provided, the module will be called withFilterPanelAPI objectas the value of this argument. (Seeteal.slice::FilterPanelAPI).

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

ui

(function)shiny UI module function with following arguments:

  • id -teal will set propershiny namespace for this module.

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

filters

(character) Deprecated. Usedatanames 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.

  • Iftransformators are specified, theirdatanames are automatically added to thisdatanamesargument.

server_args

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

ui_args

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

transformators

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

...
  • Formodules(): (teal_module orteal_modules) Objects to wrap into a tab.

  • Forformat() andprint(): Arguments passed to other methods.

x

(teal_module orteal_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 informat.teal_modules(). Determines whether to show "TEAL ROOT" header

Details

module() creates an instance of ateal_module that can be placed in ateal application.modules() shapes the structure of a the application by organizingteal_module within the navigation panel.It wrapsteal_module andteal_modules objects in ateal_modules object,which results in a nested structure corresponding to the nested tabs in the final application.

Note that formodules()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 reservedbecause they are used by themapping argument ofteal_slices()and the report previewer modulereporter_previewer_module(), respectively.

Value

module() returns an object of classteal_module.

modules() returns an object of classteal_modules.

Restricting datasets used byteal_module:

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

Whendatanames 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 inteal_data by the dot (.) are not displayed in theteal application.Please see the"Hidden datasets" section in 'vignette("including-data-in-teal-applications").

datanames withtransformators

When transformators are specified, theirdatanames are added to the module'sdatanames, whichchanges 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 forteal applications

Description

Specify initial filter states and filtering settings for ateal 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 ofteal_slice objects.

include_varnames,exclude_varnames

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

count_type

This is a new feature. Do kindly share your opinions onteal.slice's GitHub repository.

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

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

  • "all" to have counts of singleFilterState to show number of observation in filteredand unfiltered dataset. Note, that issues were reported when using this option withMultiAssayExperiment.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 - seemapping argument.

mapping

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

(namedlist) specifies which filters will be active in which modules on app start.Elements should contain character vector ofteal_sliceids (seeteal.slice::teal_slice).Names of the list should correspond toteal_modulelabel set inmodule() 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.

  • Ifmodule_specific isFALSE, onlyglobal_filters will be active on start.

app_id

(character(1))For internal use only, do not set manually.Added byinit so that ateal_slices can be matched to the app in which it was used.Used for verifying snapshots uploaded from file. Seesnapshot.

x

(list) of lists to convert toteal_slices

Details

Produces ateal_slices object.Theteal_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

Ateal_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 forteal transformations and output customization

Description

[Experimental]

teal_transform_module provides ashiny module that enables data transformations within ateal applicationand 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 takeid argument

server

(⁠function(id, data)⁠ orexpression)Ashiny module server function that takesid anddata as arguments, whereid is the module id anddatais the reactiveteal_data input. Theserver function must return a reactive expression containing ateal_dataobject. For simplified syntax, usemake_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 specifieddatanames will be displayedin the filter panel. The keyword"all" can be used to display filters for all datasets.datanames areautomatically appended to themodules()datanames.

Transforming Module Inputs inteal

Data transformations occur after data has been filtered inteal.The transformed data is then passed to theserver ofteal_module() and managed byteal's internal processes.The primary advantage ofteal_transform_module over custom modules is in its error handling, where all warnings anderrors are managed byteal, 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 withinteal.data::teal_data.This means you can use it to customize not only datasets but also tables, listings, and graphs.Someteal_modules permit developers to inject customshiny modules to enhance displayed outputs.To manage thesedecorators within your module, useui_transform_teal_data() andsrv_transform_teal_data().(For further guidance on managing decorators, refer toui_args andsrv_args in the vignette documentation.)

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

server as a language

Theserver function inteal_transform_module must return a reactiveteal.data::teal_data object.For simple transformations without complex reactivity, theserver 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 usingmake_teal_transform_server, wherelevel is automatically matched to thecorrespondinginput 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 ofteal::init

Description

Checks if the input of the title fromteal::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

This function is a wrapper forshiny::validate.

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 inx.

complete

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

allow_inf

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

msg

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

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

This function is a wrapper forshiny::validate.

Usage

validate_has_elements(x, msg)

Arguments

x

vector

msg

message to display

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

This function is a wrapper forshiny::validate.

Usage

validate_has_variable(data, varname, msg)

Arguments

data

(data.frame)

varname

(character(1)) name of variable to check for indata

msg

(character(1)) message to display ifdata does not includevarname

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

This function is a wrapper forshiny::validate.

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 ofx are not elements ofchoices.

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 fromInputValidator objects and collates theminto one message passed tovalidate.

Usage

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

Arguments

...

either any number ofInputValidator objectsor an optionally named, possibly nestedlist ofInputValidatorobjects, seeDetails

header

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

Details

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

The... argument accepts any number ofInputValidator objectsor a nested list of such objects.Ifvalidators are passed directly, all their messages are printed togetherunder one (optional) header message specified byheader. If a list is passed,messages are grouped byvalidator. The list's names are used as headersfor their respective message groups.If neither of the nested list elements is named, a header message is taken fromheader.

Value

Returns NULL if the final validation call passes and ashiny.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

If the number of levels ofx is less thanmin_levelsor greater thanmax_levels the validation will fail.This function is a wrapper forshiny::validate.

Usage

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

Arguments

x

variable name. Ifx is not a factor, the unique valuesare treated as levels.

min_levels

cutoff for minimum number of levels ofx

max_levels

cutoff for maximum number of levels ofx

var_name

name of variable being validated for use invalidation message

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

This function is a wrapper forshiny::validate.

Usage

validate_no_intersection(x, y, msg)

Arguments

x

vector

y

vector

msg

(character(1)) message to display ifx andy intersect

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

This function is a wrapper forshiny::validate.

Usage

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

Arguments

x

(data.frame)

key

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

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)}

[8]ページ先頭

©2009-2025 Movatter.jp