| Type: | Package |
| Title: | Exploratory Web Apps for Analyzing Clinical Trials Data |
| Version: | 1.0.0 |
| Date: | 2025-08-18 |
| 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), 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.2 |
| Collate: | 'TealAppDriver.R' 'checkmate.R' 'dummy_functions.R' 'include_css_js.R' 'modules.R' 'init.R' 'landing_popup_module.R' 'module_bookmark_manager.R' 'module_data_summary.R' 'module_filter_data.R' 'module_filter_manager.R' 'module_init_data.R' 'module_nested_tabs.R' 'module_session_info.R' 'module_snapshot_manager.R' 'module_teal.R' 'module_teal_data.R' 'module_teal_lockfile.R' 'module_teal_with_splash.R' 'module_transform_data.R' 'reporter_previewer_module.R' 'show_rcode_modal.R' 'tdata.R' 'teal.R' 'teal_data_module.R' 'teal_data_module-eval_code.R' 'teal_data_module-within.R' 'teal_data_utils.R' 'teal_modifiers.R' 'teal_reporter.R' 'teal_slices-store.R' 'teal_slices.R' 'teal_transform_module.R' 'utils.R' 'validate_inputs.R' 'validations.R' 'zzz.R' |
| NeedsCompilation: | no |
| Packaged: | 2025-08-20 08:36:26 UTC; dawidkaledkowski |
| Author: | Dawid Kaledkowski |
| Maintainer: | Dawid Kaledkowski <dawid.kaledkowski@roche.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-08-20 09:20:02 UTC |
teal: Interactive exploration of clinical trials data
Description
The teal package provides a shiny based framework for creating an
interactive data analysis environment.
Details
To learn mode about the package, visit the project website
or read the init() manual page.
Author(s)
Maintainer: Dawid Kaledkowski dawid.kaledkowski@roche.com (ORCID)
Authors:
Pawel Rucki pawel.rucki@roche.com
Aleksander Chlebowski aleksander.chlebowski@contractors.roche.com (ORCID)
Andre Verissimo andre.verissimo@roche.com (ORCID)
Kartikeya Kirar kartikeya.kirar@businesspartner.roche.com
Vedha Viyash vedha.viyash@roche.com
Marcin Kosinski marcin.kosinski.mk1@roche.com
Adrian Waddell adrian.waddell@gene.com
Nikolas Burkoff
Mahmoud Hallal
Maciej Nasinski
Konrad Pagacz
Junlue Zhao
Tadeusz Lewandowski
Other contributors:
Dony Unardi unardid@gene.com [reviewer]
Nina Qi qi.ting@gene.com [reviewer]
Chendi Liao [reviewer]
F. Hoffmann-La Roche AG [copyright holder, funder]
Maximilian Mordig [contributor]
See Also
Useful links:
Report bugs at https://github.com/insightsengineering/teal/issues
Adds signature protection to the datanames in the data
Description
Adds signature protection to the datanames in the data
Usage
.add_signature_to_data(data)
Arguments
data |
( |
Value
teal_data with additional code that has signature of the datanames
Calls expression when condition is met
Description
Function postpones handlerExpr to the moment when eventExpr (condition) returns TRUE,
otherwise nothing happens.
Usage
.call_once_when(
eventExpr,
handlerExpr,
event.env = parent.frame(),
handler.env = parent.frame(),
...
)
Arguments
eventExpr |
A (quoted or unquoted) logical expression that represents the event; this can be a simple reactive value like input$click, a call to a reactive expression like dataset(), or even a complex expression inside curly braces. |
handlerExpr |
The expression to call whenever |
event.env |
The parent environment for the reactive expression. By default,
this is the calling environment, the same as when defining an ordinary
non-reactive expression. If |
handler.env |
The parent environment for the reactive expression. By default,
this is the calling environment, the same as when defining an ordinary
non-reactive expression. If |
... |
additional arguments passed to |
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 |
( |
datanames |
( |
Value
A character vector with the code lines.
Temporary function to handle server_args of the report_previewer_module before its hard deprecation.
Description
Temporary function to handle server_args of the report_previewer_module before its hard deprecation.
Usage
.get_reporter_options(args)
Arguments
args |
( |
Smart rbind
Description
Combine data.frame objects which have different columns
Usage
.smart_rbind(...)
Arguments
... |
( |
The default favicon for the teal app.
Description
The default favicon for the teal app.
Usage
.teal_favicon
Format
An object of class character of length 1.
Drive a teal application
Description
Drive a teal application
Drive a teal application
Details
Extension of the shinytest2::AppDriver class with methods for
driving a teal application for performing interactions for shinytest2 tests.
Super class
shinytest2::AppDriver -> TealAppDriver
Methods
Public methods
Inherited methods
shinytest2::AppDriver$expect_download()shinytest2::AppDriver$expect_html()shinytest2::AppDriver$expect_js()shinytest2::AppDriver$expect_screenshot()shinytest2::AppDriver$expect_text()shinytest2::AppDriver$expect_unique_names()shinytest2::AppDriver$expect_values()shinytest2::AppDriver$get_chromote_session()shinytest2::AppDriver$get_dir()shinytest2::AppDriver$get_download()shinytest2::AppDriver$get_html()shinytest2::AppDriver$get_js()shinytest2::AppDriver$get_logs()shinytest2::AppDriver$get_screenshot()shinytest2::AppDriver$get_text()shinytest2::AppDriver$get_url()shinytest2::AppDriver$get_value()shinytest2::AppDriver$get_values()shinytest2::AppDriver$get_variant()shinytest2::AppDriver$get_window_size()shinytest2::AppDriver$log_message()shinytest2::AppDriver$run_js()shinytest2::AppDriver$set_inputs()shinytest2::AppDriver$set_window_size()shinytest2::AppDriver$stop()shinytest2::AppDriver$upload_file()shinytest2::AppDriver$view()shinytest2::AppDriver$wait_for_idle()shinytest2::AppDriver$wait_for_js()shinytest2::AppDriver$wait_for_value()
Method new()
Initialize a TealAppDriver object for testing a teal application.
Usage
TealAppDriver$new( data, modules, filter = teal_slices(), title_args = list(), header = tags$p(), footer = tags$p(), landing_popup_args = NULL, timeout = rlang::missing_arg(), load_timeout = rlang::missing_arg(), ... )
Arguments
data, modules, filterarguments passed to
inittitle_args, header, footer, landing_popup_argsto pass into the modifier functions.
timeout(
numeric) Default number of milliseconds for any timeout or timeout_ parameter in theTealAppDriverclass. Defaults to 20s.See
shinytest2::AppDrivernewmethod for more details on how to change it via options or environment variables.load_timeout(
numeric) How long to wait for the app to load, in ms. This includes the time to start R. Defaults to 100s.See
shinytest2::AppDrivernewmethod for more details on how to change it via options or environment variables...Additional arguments to be passed to
shinytest2::AppDriver$new
Returns
Object of class TealAppDriver
Method click()
Append parent shinytest2::AppDriver click method with a call to waif_for_idle() method.
Usage
TealAppDriver$click(...)
Arguments
...arguments passed to parent
shinytest2::AppDriverclick()method.
Method expect_no_shiny_error()
Check if the app has shiny errors. This checks for global shiny errors. Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab is visited because shiny will not trigger server computations when the tab is invisible. So, navigate to the module tab you want to test before calling this function. Although, this catches errors hidden in the other module tabs if they are already rendered.
Usage
TealAppDriver$expect_no_shiny_error()
Method expect_no_validation_error()
Check if the app has no validation errors. This checks for global shiny validation errors.
Usage
TealAppDriver$expect_no_validation_error()
Method expect_validation_error()
Check if the app has validation errors. This checks for global shiny validation errors.
Usage
TealAppDriver$expect_validation_error()
Method set_input()
Set the input in the teal app.
Usage
TealAppDriver$set_input(input_id, value, ...)
Arguments
input_id(character) The shiny input id with it's complete name space.
valueThe value to set the input to.
...Additional arguments to be passed to
shinytest2::AppDriver$set_inputs
Returns
The TealAppDriver object invisibly.
Method navigate_teal_tab()
Navigate the teal tabs in the teal app.
Usage
TealAppDriver$navigate_teal_tab(tab)
Arguments
tab(character) Labels of tabs to navigate to. Note: Make sure to provide unique labels for the tabs.
Returns
The TealAppDriver object invisibly.
Method active_ns()
Get the active shiny name space for different components of the teal app.
Usage
TealAppDriver$active_ns()
Returns
(list) The list of active shiny name space of the teal components.
Method active_module_ns()
Get the active shiny name space for interacting with the module content.
Usage
TealAppDriver$active_module_ns()
Returns
(string) The active shiny name space of the component.
Method active_module_element()
Get the active shiny name space bound with a custom element name.
Usage
TealAppDriver$active_module_element(element)
Arguments
elementcharacter(1)custom element name.
Returns
(string) The active shiny name space of the component bound with the input element.
Method active_module_element_text()
Get the text of the active shiny name space bound with a custom element name.
Usage
TealAppDriver$active_module_element_text(element)
Arguments
elementcharacter(1)the text of the custom element name.
Returns
(string) The text of the active shiny name space of the component bound with the input element.
Method active_filters_ns()
Get the active shiny name space for interacting with the filter panel.
Usage
TealAppDriver$active_filters_ns()
Returns
(string) The active shiny name space of the component.
Method active_data_summary_ns()
Get the active shiny name space for interacting with the data-summary panel.
Usage
TealAppDriver$active_data_summary_ns()
Returns
(string) The active shiny name space of the data-summary component.
Method active_data_summary_element()
Get the active shiny name space bound with a custom element name.
Usage
TealAppDriver$active_data_summary_element(element)
Arguments
elementcharacter(1)custom element name.
Returns
(string) The active shiny name space of the component bound with the input element.
Method get_active_module_input()
Get the input from the module in the teal app.
This function will only access inputs from the name space of the current active teal module.
Usage
TealAppDriver$get_active_module_input(input_id)
Arguments
input_id(character) The shiny input id to get the value from.
Returns
The value of the shiny input.
Method get_active_module_output()
Get the output from the module in the teal app.
This function will only access outputs from the name space of the current active teal module.
Usage
TealAppDriver$get_active_module_output(output_id)
Arguments
output_id(character) The shiny output id to get the value from.
Returns
The value of the shiny output.
Method get_active_module_table_output()
Get the output from the module's teal.widgets::table_with_settings or DT::DTOutput in the teal app.
This function will only access outputs from the name space of the current active teal module.
Usage
TealAppDriver$get_active_module_table_output(table_id, which = 1)
Arguments
table_id(
character(1)) The id of the table in the active teal module's name space.which(integer) If there is more than one table, which should be extracted. By default it will look for a table that is built using
teal.widgets::table_with_settings.
Returns
The data.frame with table contents.
Method get_active_module_plot_output()
Get the output from the module's teal.widgets::plot_with_settings in the teal app.
This function will only access plots from the name space of the current active teal module.
Usage
TealAppDriver$get_active_module_plot_output(plot_id)
Arguments
plot_id(
character(1)) The id of the plot in the active teal module's name space.
Returns
The src attribute as character(1) vector.
Method set_active_module_input()
Set the input in the module in the teal app.
This function will only set inputs in the name space of the current active teal module.
Usage
TealAppDriver$set_active_module_input(input_id, value, ...)
Arguments
input_id(character) The shiny input id to get the value from.
valueThe value to set the input to.
...Additional arguments to be passed to
shinytest2::AppDriver$set_inputs
Returns
The TealAppDriver object invisibly.
Method get_active_filter_vars()
Get the active datasets that can be accessed via the filter panel of the current active teal module.
Usage
TealAppDriver$get_active_filter_vars()
Method get_active_data_summary_table()
Get the active data summary table
Usage
TealAppDriver$get_active_data_summary_table()
Returns
data.frame
Method is_visible()
Test if DOM elements are visible on the page with a JavaScript call.
Usage
TealAppDriver$is_visible( selector, content_visibility_auto = FALSE, opacity_property = FALSE, visibility_property = FALSE )
Arguments
selector(
character(1))CSSselector to check visibility. ACSSid will return only one element if the UI is well formed.content_visibility_auto, opacity_property, visibility_property(
logical(1)) See more information on https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility.
Returns
Logical vector with all occurrences of the selector.
Method get_active_data_filters()
Get the active filter variables from a dataset in the teal app.
Usage
TealAppDriver$get_active_data_filters(dataset_name = NULL)
Arguments
dataset_name(character) The name of the dataset to get the filter variables from. If
NULL, the filter variables for all the datasets will be returned in a list.
Method add_filter_var()
Add a new variable from the dataset to be filtered.
Usage
TealAppDriver$add_filter_var(dataset_name, var_name, ...)
Arguments
dataset_name(character) The name of the dataset to add the filter variable to.
var_name(character) The name of the variable to add to the filter panel.
...Additional arguments to be passed to
shinytest2::AppDriver$set_inputs
Returns
The TealAppDriver object invisibly.
Method remove_filter_var()
Remove an active filter variable of a dataset from the active filter variables panel.
Usage
TealAppDriver$remove_filter_var(dataset_name = NULL, var_name = NULL)
Arguments
dataset_name(character) The name of the dataset to remove the filter variable from. If
NULL, all the filter variables will be removed.var_name(character) The name of the variable to remove from the filter panel. If
NULL, all the filter variables of the dataset will be removed.
Returns
The TealAppDriver object invisibly.
Method set_active_filter_selection()
Set the active filter values for a variable of a dataset in the active filter variable panel.
Usage
TealAppDriver$set_active_filter_selection(dataset_name, var_name, input, ...)
Arguments
dataset_name(character) The name of the dataset to set the filter value for.
var_name(character) The name of the variable to set the filter value for.
inputThe value to set the filter to.
...Additional arguments to be passed to
shinytest2::AppDriver$set_inputs
Returns
The TealAppDriver object invisibly.
Method get_attr()
Extract html attribute (found by a selector).
Usage
TealAppDriver$get_attr(selector, attribute)
Arguments
selector(
character(1)) specifying the selector to be used to get the content of a specific node.attribute(
character(1)) name of an attribute to retrieve from a node specified byselector.
Returns
The character vector.
Method get_html_rvest()
Wrapper around get_html that passes the output directly to rvest::read_html.
Usage
TealAppDriver$get_html_rvest(selector)
Arguments
selector(character(1))passed toget_html.
Returns
An XML document.
Wrapper around get_url() method that opens the app in the browser.
Method open_url()
Usage
TealAppDriver$open_url()
Returns
Nothing. Opens the underlying teal app in the browser.
Method wait_for_active_module_value()
Waits until a specified input, output, or export value.
This function serves as a wrapper around the wait_for_value method,
providing a more flexible interface for waiting on different types of values within the active module namespace.
Usage
TealAppDriver$wait_for_active_module_value( input = rlang::missing_arg(), output = rlang::missing_arg(), export = rlang::missing_arg(), ... )
Arguments
input, output, exportA name of an input, output, or export value. Only one of these parameters may be used.
...Must be empty. Allows for parameter expansion. Parameter with additional value to passed in
wait_for_value.
TealReportCard
Description
Child class of
teal.reporter::ReportCard that is used for teal specific applications.
In addition to the parent methods, it supports rendering teal specific elements such as
the source code, the encodings panel content and the filter panel content as part of the
meta data.
Super class
teal.reporter::ReportCard -> TealReportCard
Methods
Public methods
Inherited methods
teal.reporter::ReportCard$append_content()teal.reporter::ReportCard$append_html()teal.reporter::ReportCard$append_metadata()teal.reporter::ReportCard$append_plot()teal.reporter::ReportCard$append_rcode()teal.reporter::ReportCard$append_table()teal.reporter::ReportCard$append_text()teal.reporter::ReportCard$from_list()teal.reporter::ReportCard$get_content()teal.reporter::ReportCard$get_metadata()teal.reporter::ReportCard$get_name()teal.reporter::ReportCard$initialize()teal.reporter::ReportCard$reset()teal.reporter::ReportCard$set_name()teal.reporter::ReportCard$to_list()
Method append_src()
Appends the source code to the content meta data of this TealReportCard.
Usage
TealReportCard$append_src(src, ...)
Arguments
src(
character(1)) code as text....any
rmarkdownRchunk parameter and its value. Butevalparameter is always set toFALSE.
Returns
Object of class TealReportCard, invisibly.
Examples
card <- TealReportCard$new()$append_src( "plot(iris)" ) card$get_content()[[1]]$get_content()
Method append_fs()
Appends the filter state list to the content and metadata of this TealReportCard.
If the filter state list has an attribute named formatted, it appends it to the card otherwise it uses
the default yaml::as.yaml to format the list.
If the filter state list is empty, nothing is appended to the content.
Usage
TealReportCard$append_fs(fs)
Arguments
fs(
teal_slices) object returned fromteal_slices()function.
Returns
self, invisibly.
Method append_encodings()
Appends the encodings list to the content and metadata of this TealReportCard.
Usage
TealReportCard$append_encodings(encodings)
Arguments
encodings(
list) list of encodings selections of thetealapp.
Returns
self, invisibly.
Examples
card <- TealReportCard$new()$append_encodings(list(variable1 = "X")) card$get_content()[[1]]$get_content()
Method clone()
The objects of this class are cloneable with this method.
Usage
TealReportCard$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
## ------------------------------------------------
## Method `TealReportCard$append_src`
## ------------------------------------------------
card <- TealReportCard$new()$append_src(
"plot(iris)"
)
card$get_content()[[1]]$get_content()
## ------------------------------------------------
## Method `TealReportCard$append_encodings`
## ------------------------------------------------
card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))
card$get_content()[[1]]$get_content()
TealSlicesBlock
Description
Specialized TealSlicesBlock block for managing filter panel content in reports.
Super classes
teal.reporter::ContentBlock -> teal.reporter::TextBlock -> TealSlicesBlock
Methods
Public methods
Inherited methods
Method new()
Returns a TealSlicesBlock object.
Usage
TealSlicesBlock$new(content = teal_slices(), style = "verbatim")
Arguments
content(
teal_slices) object returned fromteal_slices()function.style(
character(1)) string specifying style to apply.
Details
Returns a TealSlicesBlock object with no content and no parameters.
Returns
Object of class TealSlicesBlock, invisibly.
Method set_content()
Sets content of this TealSlicesBlock.
Sets content as YAML text which represents a list generated from teal_slices.
The list displays limited number of fields from teal_slice objects, but this list is
sufficient to conclude which filters were applied.
When selected field in teal_slice object is a range, then it is displayed as a "min"
Usage
TealSlicesBlock$set_content(content)
Arguments
content(
teal_slices) object returned fromteal_slices()function.
Returns
self, invisibly.
Method from_list()
Create the TealSlicesBlock from a list.
Usage
TealSlicesBlock$from_list(x)
Arguments
x(
named list) with two fieldstextandstyle. Use theget_available_stylesmethod to get all possible styles.
Returns
self, invisibly.
Examples
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$from_list(list(text = "sth", style = "default"))
Method to_list()
Convert the TealSlicesBlock to a list.
Usage
TealSlicesBlock$to_list()
Returns
named list with a text and style.
Examples
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$to_list()
Method clone()
The objects of this class are cloneable with this method.
Usage
TealSlicesBlock$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
Examples
## ------------------------------------------------
## Method `TealSlicesBlock$from_list`
## ------------------------------------------------
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$from_list(list(text = "sth", style = "default"))
## ------------------------------------------------
## Method `TealSlicesBlock$to_list`
## ------------------------------------------------
TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")
block <- TealSlicesBlock$new()
block$to_list()
Add a Landing Popup to teal Application
Description
Adds a landing popup to the teal app. This popup will be shown when the app starts.
The dialog must be closed by the app user to proceed to the main application.
Usage
add_landing_modal(
x,
title = NULL,
content = NULL,
footer = modalButton("Accept"),
...
)
Arguments
x |
( |
title |
An optional title for the dialog. |
content |
( |
footer |
UI for footer. Use |
... |
Additional arguments to |
Examples in Shinylive
- example-1
Examples
app <- init(
data = teal_data(IRIS = iris, MTCARS = mtcars),
modules = modules(example_module())
) |>
add_landing_modal(
title = "Welcome",
content = "This is a landing popup.",
buttons = modalButton("Accept")
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
Append a teal_module to children of a teal_modules object
Description
Append a teal_module to children of a teal_modules object
Usage
append_module(modules, module)
Arguments
modules |
( |
module |
( |
Value
A teal_modules object with module appended.
Compare bookmarks.
Description
Test if two bookmarks store identical state.
Usage
bookmarks_identical(book1, book2)
Arguments
book1, book2 |
bookmark directories stored in |
Details
input environments are compared one variable at a time and if not identical,
values in both bookmarks are reported. States of datatables are stripped
of the time element before comparing because the time stamp is always different.
The contents themselves are not printed as they are large and the contents are not informative.
Elements present in one bookmark and absent in the other are also reported.
Differences are printed as messages.
values environments are compared with all.equal.
Value
Invisible NULL if bookmarks are identical or if there are no bookmarks to test.
FALSE if inconsistencies are detected.
How to use
Open an application, change relevant inputs (typically, all of them), and create a bookmark. Then open that bookmark and immediately create a bookmark of that. If restoring bookmarks occurred properly, the two bookmarks should store the same state.
Build app title with favicon
Description
A helper function to create the browser title along with a logo.
Usage
build_app_title(
title = "teal app",
favicon =
"https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png"
)
Arguments
title |
( |
favicon |
( |
Value
A shiny.tag containing the element that adds the title and logo to the shiny app.
Check datanames in filters
Description
This function checks whether datanames in filters correspond to those in data,
returning character vector with error messages or TRUE if all checks pass.
Usage
check_filter_datanames(filters, datanames)
Arguments
filters |
( |
datanames |
( |
Value
A character(1) containing error message or TRUE if validation passes.
Check datanames in modules
Description
These functions check if specified datanames in modules match those in the data object,
returning error messages or TRUE for successful validation. Two functions return error message
in different forms:
-
check_modules_datanamesreturnscharacter(1)for basic assertion usage -
check_modules_datanames_htmlreturnsshiny.tag.listto display it in the app.
Usage
check_modules_datanames(modules, datanames)
check_reserved_datanames(datanames)
check_modules_datanames_html(modules, datanames)
Arguments
modules |
( |
datanames |
( |
Value
TRUE if validation passes, otherwise character(1) or shiny.tag.list
Check that argument is reactive.
Description
Check that argument is reactive.
Usage
check_reactive(x, null.ok = FALSE)
test_reactive(x, null.ok = FALSE)
assert_reactive(
x,
null.ok = FALSE,
.var.name = checkmate::vname(x),
add = NULL
)
Arguments
x |
[ |
null.ok |
[ |
.var.name |
[ |
add |
[ |
Value
Depending on the function prefix:
If the check is successful, the functions
assertClass/assert_class return
x invisibly, whereas
checkClass/check_class and
testClass/test_class return
TRUE.
If the check is not successful,
assertClass/assert_class
throws an error message,
testClass/test_class
returns FALSE,
and checkClass/check_class
return a string with the error message.
The function expect_class always returns an
expectation.
Application ID
Description
Creates App ID used to match filter snapshots to application.
Usage
create_app_id(data, modules)
Arguments
data |
( |
modules |
( |
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 |
( |
post |
( |
Value
x if no error, otherwise throws error with decorated message
Deep copy teal_slices
Description
it's important to create a new copy of teal_slices when
starting a new shiny session. Otherwise, object will be shared
by multiple users as it is created in global environment before
shiny session starts.
Usage
deep_copy_filter(filter)
Arguments
filter |
( |
Value
teal_slices
An example teal module
Description
This module creates an object called object that can be modified with decorators.
The object is determined by what's selected in Choose a dataset input in UI.
The object can be anything that can be handled by renderPrint().
See the vignette("transform-module-output", package = "teal") or teal_transform_module
to read more about decorators.
Usage
example_module(
label = "example teal module",
datanames = "all",
transformators = list(),
decorators = list()
)
Arguments
Value
A teal module which can be included in the modules argument to init().
Examples in Shinylive
- example-1
Examples
app <- init(
data = teal_data(IRIS = iris, MTCARS = mtcars),
modules = example_module()
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
Extract/Remove module(s) of specific class
Description
Given a teal_module or a teal_modules, return the elements of the structure according to class.
Usage
extract_module(modules, class)
drop_module(modules, class)
Arguments
modules |
( |
class |
The class name of |
Value
For
extract_module, ateal_moduleof classclassorteal_modulescontaining modules of classclass.For
drop_module, the opposite, which is allteal_modulesof class other thanclass.
teal_modules
Extract all transformators from modules.
Description
Extract all transformators from modules.
Usage
extract_transformators(modules)
Arguments
modules |
|
Value
A list of teal_transform_module nested in the same way as input modules.
Get client timezone
Description
User timezone in the browser may be different to the one on the server.
This script can be run to register a shiny input which contains information about the timezone in the browser.
Usage
get_client_timezone(ns)
Arguments
ns |
( |
Value
NULL, invisibly.
Get unique labels
Description
Get unique labels for the modules to avoid namespace conflicts.
Usage
get_unique_labels(labels)
Arguments
labels |
( |
Value
(character) vector of unique labels
Include CSS files from /inst/css/ package directory to application header
Description
system.file should not be used to access files in other packages, it does
not work with devtools. Therefore, we redefine this method in each package
as needed. Thus, we do not export this method.
Usage
include_css_files(pattern = "*")
Arguments
pattern |
( |
Value
HTML code that includes CSS files.
Code to include teal CSS and JavaScript files
Description
This is useful when you want to use the same JavaScript and CSS files that are
used with the teal application.
This is also useful for running standalone modules in teal with the correct
styles.
Also initializes shinyjs so you can use it.
Usage
include_teal_css_js()
Details
Simply add include_teal_css_js() as one of the UI elements.
Value
A shiny.tag.list.
Create the server and UI function for the shiny app
Description
End-users: This is the most important function for you to start a
teal app that is composed of teal modules.
Usage
init(
data,
modules,
filter = teal_slices(),
title = lifecycle::deprecated(),
header = lifecycle::deprecated(),
footer = lifecycle::deprecated(),
id = lifecycle::deprecated()
)
Arguments
data |
( |
modules |
( |
filter |
( |
title |
( |
header |
( |
footer |
( |
id |
|
Value
Named list containing server and UI functions.
Examples in Shinylive
- example-1
Examples
app <- init(
data = within(
teal_data(),
{
new_iris <- transform(iris, id = seq_len(nrow(iris)))
new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))
}
),
modules = modules(
module(
label = "data source",
server = function(input, output, session, data) {},
ui = function(id, ...) tags$div(p("information about data source")),
datanames = "all"
),
example_module(label = "example teal module"),
module(
"Iris Sepal.Length histogram",
server = function(input, output, session, data) {
output$hist <- renderPlot(
hist(data()[["new_iris"]]$Sepal.Length)
)
},
ui = function(id, ...) {
ns <- NS(id)
plotOutput(ns("hist"))
},
datanames = "new_iris"
)
),
filter = teal_slices(
teal_slice(dataname = "new_iris", varname = "Species"),
teal_slice(dataname = "new_iris", varname = "Sepal.Length"),
teal_slice(dataname = "new_mtcars", varname = "cyl"),
exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),
module_specific = TRUE,
mapping = list(
`example teal module` = "new_iris Species",
`Iris Sepal.Length histogram` = "new_iris Species",
global_filters = "new_mtcars cyl"
)
)
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
Does the object make use of the arg
Description
Does the object make use of the arg
Usage
is_arg_used(modules, arg)
Arguments
modules |
( |
arg |
( |
Value
logical whether the object makes use of arg.
Landing popup module
Description
Creates a landing welcome popup for
teal applications.
This module is used to display a popup dialog when the application starts.
The dialog blocks access to the application and must be closed with a button before the application can be viewed.
This function is deprecated, please use add_landing_modal() on the teal app object instead.
Usage
landing_popup_module(
label = "Landing Popup",
title = NULL,
content = NULL,
buttons = modalButton("Accept")
)
Arguments
label |
( |
title |
( |
content |
( |
buttons |
( |
Value
A teal_module (extended with teal_landing_module class) to be used in teal applications.
Make teal_transform_module's server
Description
A factory function to simplify creation of a teal_transform_module's server. Specified expr
is wrapped in a shiny module function and output can be passed to the server argument in
teal_transform_module() call. Such a server function can be linked with ui and values from the
inputs can be used in the expression. Object names specified in the expression will be substituted
with the value of the respective input (matched by the name) - for example in
expression(graph <- graph + ggtitle(title)) object title will be replaced with the value of
input$title.
Usage
make_teal_transform_server(expr)
Arguments
expr |
( |
Value
function(id, data) returning shiny module
Examples in Shinylive
- example-1
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
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 |
( |
modules |
( |
Details
This module introduces bookmarks into teal apps: the shiny bookmarking mechanism becomes enabled
and server-side bookmarks can be created.
The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.
teal does not guarantee that all modules (teal_module objects) are bookmarkable.
Those that are, have a teal_bookmarkable attribute set to TRUE. If any modules are not bookmarkable,
the bookmark manager modal displays a warning and the bookmark button displays a flag.
In order to communicate that a external module is bookmarkable, the module developer
should set the teal_bookmarkable attribute to TRUE.
Value
Invisible NULL.
Server logic
A bookmark is a URL that contains the app address with a /?_state_id_=<bookmark_dir> suffix.
<bookmark_dir> is a directory created on the server, where the state of the application is saved.
Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.
Note
To enable bookmarking use either:
-
shinyapp by usingshinyApp(..., enableBookmarking = "server")(not supported inshinytest2) set
options(shiny.bookmarkStore = "server")before running the app
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 |
( |
data |
( |
current_data |
( |
initial_data |
( |
dataname |
( |
subject_keys |
( |
Details
Handling different data classes:
get_filter_overview() is a pseudo S3 method which has variants for:
-
array(data.frame,DataFrame,array,MatrixandSummarizedExperiment): Method variant can be applied to any two-dimensional objects on whichncol()can be used. -
MultiAssayExperiment: for which summary contains counts forcolDataand allexperiments. For other data types module displays data name with warning icon and no more details.
Module includes also "Show/Hide unsupported" button to toggle rows of the summary table containing datasets where number of observations are not calculated.
Value
NULL.
Filter panel module in teal
Description
Creates filter panel module from teal_data object and returns teal_data. It is build in a way
that filter panel changes and anything what happens before (e.g. module_init_data) is triggering
further reactive events only if something has changed and if the module is visible. Thanks to
this special implementation all modules' data are recalculated only for those modules which are
currently displayed.
Usage
ui_filter_data(id)
srv_filter_data(id, datasets, active_datanames, data, is_active)
.make_filtered_teal_data(modules, data, datasets = NULL, datanames)
.observe_active_filter_changed(datasets, is_active, active_datanames, data)
.get_filter_expr(datasets, datanames)
Arguments
id |
( |
datasets |
( |
active_datanames |
( |
data |
( |
modules |
( |
Value
A eventReactive containing teal_data containing filtered objects and filter code.
eventReactive triggers only if all conditions are met:
tab is selected (
is_active)when filters are changed (
get_filter_expris different than previous)
Manage multiple FilteredData objects
Description
Oversee filter states across the entire application.
Usage
ui_filter_manager_panel(id)
srv_filter_manager_panel(id, slices_global)
ui_filter_manager(id)
srv_filter_manager(id, slices_global)
srv_module_filter_manager(id, module_fd, slices_global)
Arguments
id |
( |
slices_global |
( |
module_fd |
( |
Value
Module returns a slices_global (reactiveVal) containing a teal_slices object with mapping.
Slices global
The key role in maintaining the module-specific filter states is played by the .slicesGlobal
object. It is a reference class that holds the following fields:
-
all_slices(reactiveVal) - reactive value containing all filters registered in an app. -
module_slices_api(reactiveValues) - reactive field containing references to each modules'FilteredDataobject methods. At this moment it is used only insrv_filter_managerto display the filter states in a table combining informations fromall_slicesand fromFilteredData$get_available_teal_slices().
During a session only new filters are added to all_slices unless module_snapshot_manager is
used to restore previous state. Filters from all_slices can be activated or deactivated in a
module which is linked (both ways) by attr(, "mapping") so that:
If module's filter is added or removed in its
FilteredDataobject, this information is passed toSlicesGlobalwhich updatesattr(, "mapping")accordingly.When mapping changes in a
SlicesGlobal, filters are set or removed from module'sFilteredData.
Filter manager
Filter-manager is split into two parts:
-
ui/srv_filter_manager_panel- Called once for the whole app. This module observes changes in the filters inslices_globaland displays them in a table utilizing information frommapping:
(
TRUE) - filter is active in the module(
FALSE) - filter is inactive in the module(
NA) - filter is not available in the module
-
ui/srv_module_filter_manager- Called once for eachteal_module. Handling filter states for of single module and keeping moduleFilteredDataconsistent withslices_global, so that local filters are always reflected in theslices_globaland its mapping and vice versa.
Data Module for teal
Description
This module manages the data argument for srv_teal. The teal framework uses teal.data::teal_data(),
which can be provided in various ways:
Directly as a
teal.data::teal_data()object. This will automatically convert it into areactiveteal_data.As a
reactiveobject that returns ateal.data::teal_data()object.
Usage
ui_init_data(id)
srv_init_data(id, data)
Arguments
id |
( |
data |
( |
Details
Reactive teal_data:
The data in the application can be reactively updated, prompting srv_teal() to rebuild the
content accordingly. There are two methods for creating interactive teal_data:
Using a
reactiveobject provided from outside thetealapplication. In this scenario, reactivity is controlled by an external module, andsrv_tealresponds to changes.Using
teal_data_module(), which is embedded within thetealapplication, allowing data to be resubmitted by the user as needed.
Since the server of teal_data_module() must return a reactive teal_data object, both
methods (1 and 2) produce the same reactive behavior within a teal application. The distinction
lies in data control: the first method involves external control, while the second method
involves control from a custom module within the app.
For more details, see module_teal_data.
Value
A reactive object that returns:
Output of the data. If data fails then returned error is handled (after tryCatch()) so that
rest of the application can respond to this respectively.
teal user session info module
Description
Module to display the user session info popup and to download a lockfile. Module is included
when running init() but skipped when using module_teal. Please be aware that session info
contains R session information, so multiple module's calls will share the same information.
Usage
ui_session_info(id)
srv_session_info(id)
Arguments
id |
( |
Value
NULL invisibly
Examples in Shinylive
- example-1
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 |
( |
slices_global |
( |
Details
This module introduces snapshots: stored descriptions of the filter state of the entire application. Snapshots allow the user to save the current filter state of the application for later use in the session, as well as to save it to file in order to share it with an app developer or other users, who in turn can upload it to their own session.
The snapshot manager is accessed with the camera icon in the tabset bar. At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file and applies the filter states therein, and clicking the arrow resets initial application state. As snapshots are added, they will show up as rows in a table and each will have a select button and a save button.
Value
list containing the snapshot history, where each element is an unlisted teal_slices object.
Server logic
Snapshots are basically teal_slices objects, however, since each module is served by a separate instance
of FilteredData and these objects require shared state, teal_slice is a reactiveVal so teal_slices
cannot be stored as is. Therefore, teal_slices are reversibly converted to a list of lists representation
(attributes are maintained).
Snapshots are stored in a reactiveVal as a named list.
The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.
For every snapshot except the initial one, a piece of UI is generated that contains the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. The initial snapshot is restored by a separate "reset" button. It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.
Snapshot mechanics
When a snapshot is captured, the user is prompted to name it. Names are displayed as is but since they are used to create button ids, under the hood they are converted to syntactically valid strings. New snapshot names are validated so that their valid versions are unique. Leading and trailing white space is trimmed.
The module can read the global state of the application from slices_global and mapping_matrix.
The former provides a list of all existing teal_slices and the latter says which slice is active in which module.
Once a name has been accepted, slices_global is converted to a list of lists - a snapshot.
The snapshot contains the mapping attribute of the initial application state
(or one that has been restored), which may not reflect the current one,
so mapping_matrix is transformed to obtain the current mapping, i.e. a list that,
when passed to the mapping argument of teal_slices(), would result in the current mapping.
This is substituted as the snapshot's mapping attribute and the snapshot is added to the snapshot list.
To restore app state, a snapshot is retrieved from storage and rebuilt into a teal_slices object.
Then state of all FilteredData objects (provided in datasets) is cleared
and set anew according to the mapping attribute of the snapshot.
The snapshot is then set as the current content of slices_global.
To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,
and then saved to file with slices_store().
When a snapshot is uploaded, it will first be added to storage just like a newly created one,
and then used to restore app state much like a snapshot taken from storage.
Upon clicking the upload icon the user will be prompted for a file to upload
and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped)
and normal naming rules apply. Loading the file yields a teal_slices object,
which is disassembled for storage and used directly for restoring app state.
Transferring snapshots
Snapshots uploaded from disk should only be used in the same application they come from,
i.e. an application that uses the same data and the same modules.
To ensure this is the case, init stamps teal_slices with an app id that is stored in the app_id attribute of
a teal_slices object. When a snapshot is restored from file, its app_id is compared to that
of the current app state and only if the match is the snapshot admitted to the session.
Bookmarks
An onBookmark callback creates a snapshot of the current filter state.
This is done on the app session, not the module session.
(The snapshot will be retrieved by module_teal in order to set initial app state in a restored app.)
Then that snapshot, and the previous snapshot history are dumped into the values.rds file in <bookmark_dir>.
Author(s)
Aleksander Chlebowski
teal main module
Description
Module to create a teal app as a Shiny Module.
Usage
ui_teal(id, modules)
srv_teal(id, data, modules, filter = teal_slices())
Arguments
id |
( |
modules |
( |
data |
( |
filter |
( |
Details
This module can be used instead of init() in custom Shiny applications. Unlike init(), it doesn't
automatically include module_session_info.
Module is responsible for creating the main shiny app layout and initializing all the necessary
components. This module establishes reactive connection between the input data and every other
component in the app. Reactive change of the data passed as an argument, reloads the app and
possibly keeps all input settings the same so the user can continue where one left off.
data flow in teal application
This module supports multiple data inputs but eventually, they are all converted to reactive
returning teal_data in this module. On this reactive teal_data object several actions are
performed:
data loading in
module_init_datadata filtering in
module_filter_datadata transformation in
module_transform_data
Fallback on failure
teal is designed in such way that app will never crash if the error is introduced in any
custom shiny module provided by app developer (e.g. teal_data_module(), teal_transform_module()).
If any module returns a failing object, the app will halt the evaluation and display a warning message.
App user should always have a chance to fix the improper input and continue without restarting the session.
Value
NULL invisibly
Execute and validate teal_data_module
Description
This is a low level module to handle teal_data_module execution and validation.
teal_transform_module() inherits from teal_data_module() so it is handled by this module too.
srv_teal() accepts various data objects and eventually they are all transformed to reactive
teal.data::teal_data() which is a standard data class in whole teal framework.
Usage
ui_teal_data_module(id, data_module = function(id) NULL)
srv_teal_data_module(
id,
data_module = function(id) NULL,
modules = NULL,
validate_shiny_silent_error = TRUE,
is_transform_failed = reactiveValues()
)
ui_validate_reactive_teal_data(id)
srv_validate_reactive_teal_data(
id,
data,
modules = NULL,
validate_shiny_silent_error = FALSE,
hide_validation_error = reactive(FALSE)
)
Arguments
id |
( |
data_module |
( |
modules |
( |
validate_shiny_silent_error |
( |
is_transform_failed |
( |
data |
( |
Value
reactive teal_data
data validation
Executed teal_data_module() is validated and output is validated for consistency.
Output data is invalid if:
-
teal_data_module()is invalid if server doesn't returnreactive. Immediately crashes an app! -
reactivethrows ashiny.error- happens when module creatingteal.data::teal_data()fails. -
reactivereturnsqenv.error- happens whenteal.data::teal_data()evaluates a failing code. -
reactiveobject doesn't returnteal.data::teal_data(). -
teal.data::teal_data()object lacks anydatanamesspecified in themodulesargument.
teal (observers in srv_teal) always waits to render an app until reactive teal_data is
returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is
resolved, the app will continue to run. teal guarantees that errors in data don't crash the app
(except error 1).
Note
ui_teal_data_module was renamed from ui_teal_data.
srv_teal_data_module was renamed from srv_teal_data.
Generate lockfile for application's environment reproducibility
Description
Generate lockfile for application's environment reproducibility
Usage
ui_teal_lockfile(id)
srv_teal_lockfile(id)
.teal_lockfile_process_invoke(lockfile_path)
.renv_snapshot(lockfile_path)
.is_lockfile_deps_installed()
.is_disabled_lockfile_scenario()
Arguments
id |
( |
lockfile_path |
( |
Value
NULL
Different ways of creating lockfile
teal leverages renv::snapshot(), which offers multiple methods for lockfile creation.
-
Working directory lockfile:
teal, by default, will create animplicittype lockfile that usesrenv::dependencies()to detect all R packages in the current project's working directory. -
DESCRIPTION-based lockfile: To generate a lockfile based on aDESCRIPTIONfile in your working directory, setrenv::settings$snapshot.type("explicit"). The naming convention fortypefollowsrenv::snapshot(). For the"explicit"type, refer torenv::settings$package.dependency.fields()for theDESCRIPTIONfields included in the lockfile. -
Custom files-based lockfile: To specify custom files as the basis for the lockfile, set
renv::settings$snapshot.type("custom")and configure therenv.snapshot.filteroption.
lockfile usage
After creating the lockfile, you can restore the application's environment using renv::restore().
See Also
renv::snapshot(), renv::restore().
Calls all modules
Description
Modules create navigation bar with drop-down menu and tab content. Each teal_module is called recursively
according to the structure of modules argument. This is a custom module which utilizes shiny/Bootstrap
.nav class. modules are called with an id derived from teal_module's label and labels of its
ancestors (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 |
( |
modules |
( |
data |
( |
datasets |
( |
slices_global |
( |
reporter |
( |
data_load_status |
(
|
active_module_id |
( |
Details
Functions
-
ui/srv_teal_module- wrapper module which links drop-down buttons with modules panels. Hereinput$active_module_idis instantiated. -
.ui/srv_teal_module- recursive S3 method which calls each module -
.teal_navbar_append- wrapper forhtmltools::tagAppendChild()to add any element to navigation bar. -
.teal_navbar_insert_ui- wrapper forshiny::insertUI()to insert any element to navigation bar. -
.teal_navbar_menu- UI function to create a drop-down menu for navigation bar.
Utilizing .nav class
No extra javascript or server functionality were introduced to have navigation buttons toggle between
tab 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 the teal_module(s)
Modules are initialized only when they are active. This speeds up app initialization and on startup 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 only one can run at any given time. This makes the app more efficient by reducing unnecessary computations on server side.
Value
Output of currently active module.
-
srv_teal_module.teal_modulereturnsreactiveValcontaining output of the called module. -
srv_teal_module.teal_modulesreturns output of modules in a list following the hierarchy ofmodules
UI and server modules of teal
Description
Please use
module_teal instead.
Usage
ui_teal_with_splash(
id,
data,
modules,
title = build_app_title(),
header = tags$p(),
footer = tags$p()
)
srv_teal_with_splash(id, data, modules, filter = teal_slices())
Arguments
id |
( |
data |
( |
modules |
( |
title |
( |
header |
( |
footer |
( |
filter |
( |
Value
Returns a reactive expression containing a teal_data object when data is loaded or NULL when it is not.
Module to transform reactive teal_data
Description
Module calls teal_transform_module() in sequence so that reactive teal_data output
from one module is handed over to the following module's input.
Usage
ui_transform_teal_data(id, transformators, class = "well")
srv_transform_teal_data(
id,
data,
transformators,
modules = NULL,
is_transform_failed = reactiveValues()
)
Arguments
id |
( |
transformators |
( |
class |
(character(1)) CSS class to be added in the |
data |
( |
modules |
( |
is_transform_failed |
( |
Value
reactive teal_data
Retrieve teal_bookmarkable attribute from teal_modules
Description
Retrieve teal_bookmarkable attribute from teal_modules
Usage
modules_bookmarkable(modules)
Arguments
modules |
( |
Value
named list of the same structure as modules with TRUE or FALSE values indicating
whether the module is bookmarkable.
Retrieve slot from teal_modules
Description
Retrieve slot from teal_modules
Usage
modules_slot(modules, slot)
Arguments
modules |
( |
slot |
( |
Value
A list containing the slot of the modules.
If the modules are nested, the function returns a nested list 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 |
( |
singular |
( |
plural |
(optional |
Value
A character that correctly represents the size of the x argument.
Template function for TealReportCard creation and customization
Description
This function generates a report card with a title, an optional description, and the option to append the filter state list.
Usage
report_card_template(
title,
label,
description = NULL,
with_filter,
filter_panel_api
)
Arguments
title |
( |
label |
( |
description |
( |
with_filter |
( |
filter_panel_api |
( |
Value
(TealReportCard) populated with a title, description and filter state.
Create a teal module for previewing a report
Description
This function controls the appearance of the drop-down menu for the reporter. It is now deprecated in favor of the options:
-
teal.reporter.nav_buttons = c("preview", "download", "load", "reset")to control which buttons will be displayed in the drop-down. -
teal.reporter.rmd_output: passed toteal.reporter::download_report_button_srv() -
teal.reporter.rmd_yaml_args: passed toteal.reporter::download_report_button_srv() -
teal.reporter.global_knitr: passed toteal.reporter::download_report_button_srv()
Usage
reporter_previewer_module(label = "Report previewer", server_args = list())
Arguments
label |
( |
server_args |
(named |
Value
teal_module (extended with teal_module_previewer class) containing the teal.reporter previewer functionality.
Restore value from bookmark.
Description
Get value from bookmark or return default.
Usage
restoreValue(value, default)
Arguments
value |
( |
default |
fallback value |
Details
Bookmarks can store not only inputs but also arbitrary values.
These values are stored by onBookmark callbacks and restored by onBookmarked callbacks,
and they are placed in the values environment in the session$restoreContext field.
Using teal_data_module makes it impossible to run the callbacks
because the app becomes ready before modules execute and callbacks are registered.
In those cases the stored values can still be recovered from the session object directly.
Note that variable names in the values environment are prefixed with module name space names,
therefore, when using this function in modules, value must be run through the name space function.
Value
In an application restored from a server-side bookmark,
the variable specified by value from the values environment.
Otherwise default.
Show R code modal
Description
Use the shiny::showModal() function to show the R code inside.
Usage
show_rcode_modal(title = NULL, rcode, session = getDefaultReactiveDomain())
Arguments
title |
( |
rcode |
( |
session |
( |
References
Store and restore teal_slices object
Description
Functions that write a teal_slices object to a file in the JSON format,
and also restore the object from disk.
Usage
slices_store(tss, file)
slices_restore(file)
Arguments
tss |
( |
file |
( |
Details
Date and date time objects are stored in the following formats:
-
Dateclass is converted to the"ISO8601"standard (YYYY-MM-DD). -
POSIX*tclasses are converted to character by usingformat.POSIX*t(usetz = TRUE, tz = "UTC")(YYYY-MM-DD HH:MM:SS UTC, whereUTCis theCoordinated Universal Timetimezone short-code).
This format is assumed during slices_restore. All POSIX*t objects in
selected or choices fields of teal_slice objects are always printed in
UTC timezone as well.
Value
slices_store returns NULL, invisibly.
slices_restore returns a teal_slices object restored from the file.
See Also
Create a tdata object
Description
Recent changes in teal cause modules to fail because modules expect a tdata object
to be passed to the data argument but instead they receive a teal_data object,
which is additionally wrapped in a reactive expression in the server functions.
In order to easily adapt such modules without a proper refactor,
use this function to downgrade the data argument.
Usage
new_tdata(...)
tdata2env(...)
get_code_tdata(...)
## S3 method for class 'tdata'
join_keys(...)
get_metadata(...)
as_tdata(...)
Arguments
... |
ignored |
Value
nothing
Data module for teal applications
Description
Create a teal_data_module object and evaluate code on it with history tracking.
Usage
teal_data_module(ui, server, label = "data module", once = TRUE)
## S4 method for signature 'teal_data_module,character'
eval_code(object, code)
## S3 method for class 'teal_data_module'
within(data, expr, ...)
Arguments
ui |
( |
server |
( |
label |
( |
once |
( |
object |
( |
code |
( |
data |
( |
expr |
( |
... |
See |
Details
teal_data_module creates a shiny module to interactively supply or modify data in a teal application.
The module allows for running any code (creation and some modification) after the app starts or reloads.
The body of the server function will be run in the app rather than in the global environment.
This means it will be run every time the app starts, so use sparingly.
Pass this module instead of a teal_data object in a call to init().
Note that the server function must always return a teal_data object wrapped in a reactive expression.
See vignette vignette("data-as-shiny-module", package = "teal") for more details.
eval_code evaluates given code in the environment of the teal_data object created by the teal_data_module.
The code is added to the @code slot of the teal_data.
within is a convenience function for evaluating inline code inside the environment of a teal_data_module.
It accepts only inline expressions (both simple and compound) and allows for injecting values into expr through
the ... argument: as name:value pairs are passed to ..., name in expr will be replaced with value.
Value
teal_data_module returns a list of class teal_data_module containing two elements, ui and
server provided via arguments.
eval_code returns a teal_data_module object with a delayed evaluation of code when the module is run.
within returns a teal_data_module object with a delayed evaluation of expr when the module is run.
See Also
teal.data::teal_data, teal.code::qenv()
Examples
tdm <- teal_data_module(
ui = function(id) {
ns <- NS(id)
actionButton(ns("submit"), label = "Load data")
},
server = function(id) {
moduleServer(id, function(input, output, session) {
eventReactive(input$submit, {
data <- within(
teal_data(),
{
dataset1 <- iris
dataset2 <- mtcars
}
)
data
})
})
}
)
eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')")
within(tdm, dataset1 <- subset(dataset1, Species == "virginica"))
# use additional parameter for expression value substitution.
valid_species <- "versicolor"
within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species)
Create a FilteredData
Description
Create a FilteredData object from a teal_data object.
Usage
teal_data_to_filtered_data(x, datanames = names(x))
Arguments
x |
( |
datanames |
( |
Value
A FilteredData object.
teal_data utils
Description
In teal we need to recreate the teal_data object due to two operations:
we need to append filter-data code and objects which have been evaluated in
FilteredDataand we want to avoid double-evaluation.we need to subset
teal_datatodatanamesused by the module, to shorten obtainable R-code
Usage
.append_evaluated_code(data, code)
.append_modified_data(data, objects)
Arguments
data |
( |
code |
( |
objects |
( |
Details
Due to above recreation of teal_data object can't be done simply by using public
teal.code and teal.data methods.
Value
modified teal_data
Add a Custom Server Logic to teal Application
Description
Adds a custom server function to the teal app. This function can define additional server logic.
Usage
teal_extend_server(x, custom_server, module_id = character(0))
Arguments
x |
( |
custom_server |
( |
module_id |
( |
Replace UI Elements in teal UI objects
Description
Replace UI Elements in teal UI objects
Usage
modify_title(x, title = "teal app", favicon = NULL)
modify_header(x, element = tags$p())
modify_footer(x, element = tags$p())
Arguments
x |
( |
title |
( |
favicon |
( |
element |
Replacement UI element (shiny tag or HTML) |
Examples in Shinylive
- example-1
- example-2
- example-3
Examples
app <- init(
data = teal_data(IRIS = iris, MTCARS = mtcars),
modules = modules(example_module())
) |>
modify_title(title = "Custom title")
if (interactive()) {
shinyApp(app$ui, app$server)
}
app <- init(
data = teal_data(IRIS = iris),
modules = modules(example_module())
) |>
modify_header(element = tags$div(h3("Custom header")))
if (interactive()) {
shinyApp(app$ui, app$server)
}
app <- init(
data = teal_data(IRIS = iris),
modules = modules(example_module())
) |>
modify_footer(element = "Custom footer")
if (interactive()) {
shinyApp(app$ui, app$server)
}
Create teal_module and teal_modules objects
Description
Create a nested tab structure to embed modules in a teal application.
Usage
module(
label = "module",
server = function(id, data, ...) moduleServer(id, function(input, output, session)
NULL),
ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),
filters,
datanames = "all",
server_args = NULL,
ui_args = NULL,
transformators = list()
)
modules(..., label = 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 |
( |
server |
(
|
ui |
(
|
filters |
( |
datanames |
(
|
server_args |
(named |
ui_args |
(named |
transformators |
( |
... |
|
x |
( |
is_last |
( |
parent_prefix |
( |
what |
( |
is_root |
( |
Details
module() creates an instance of a teal_module that can be placed in a teal application.
modules() shapes the structure of a the application by organizing teal_module within the navigation panel.
It wraps teal_module and teal_modules objects in a teal_modules object,
which results in a nested structure corresponding to the nested tabs in the final application.
Note that for modules() label comes after ..., so it must be passed as a named argument,
otherwise it will be captured by ....
The labels "global_filters" and "Report previewer" are reserved
because they are used by the mapping argument of teal_slices()
and the report previewer module reporter_previewer_module(), respectively.
Value
module() returns an object of class teal_module.
modules() returns a teal_modules object which contains following fields:
-
label: taken from thelabelargument. -
children: a list containing objects passed in.... List elements are named after theirlabelattribute converted to a validshinyid.
Restricting datasets used by teal_module:
The datanames argument controls which datasets are used by the module's server. These datasets,
passed via server's data argument, are the only ones shown in the module's tab.
When datanames is set to "all", all datasets in the data object are treated as relevant.
However, this may include unnecessary datasets, such as:
Proxy variables for column modifications
Temporary datasets used to create final ones
Connection objects
Datasets which name is prefixed in teal_data by the dot (.) are not displayed in the teal application.
Please see the "Hidden datasets" section in 'vignette("including-data-in-teal-applications").
datanames with transformators
When transformators are specified, their datanames are added to the module's datanames, which
changes the behavior as follows:
If
module(datanames)isNULLand thetransformatorshave defineddatanames, the sidebar will appear showing thetransformators' datasets, instead of being hidden.If
module(datanames)is set to specific values and anytransformatorhasdatanames = "all", the module may receive extra datasets that could be unnecessary
Examples in Shinylive
- example-1
Examples
library(shiny)
module_1 <- module(
label = "a module",
server = function(id, data) {
moduleServer(
id,
module = function(input, output, session) {
output$data <- renderDataTable(data()[["iris"]])
}
)
},
ui = function(id) {
ns <- NS(id)
tagList(dataTableOutput(ns("data")))
},
datanames = "all"
)
module_2 <- module(
label = "another module",
server = function(id) {
moduleServer(
id,
module = function(input, output, session) {
output$text <- renderText("Another Module")
}
)
},
ui = function(id) {
ns <- NS(id)
tagList(textOutput(ns("text")))
},
datanames = NULL
)
modules <- modules(
label = "modules",
modules(
label = "nested modules",
module_1
),
module_2
)
app <- init(
data = teal_data(iris = iris),
modules = modules
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
mod <- module(
label = "My Custom Module",
server = function(id, data, ...) {},
ui = function(id, ...) {},
datanames = c("ADSL", "ADTTE"),
transformators = list(),
ui_args = list(a = 1, b = "b"),
server_args = list(x = 5, y = list(p = 1))
)
cat(format(mod))
custom_module <- function(
label = "label", ui_args = NULL, server_args = NULL,
datanames = "all", transformators = list(), bk = FALSE) {
ans <- module(
label,
server = function(id, data, ...) {},
ui = function(id, ...) {
},
datanames = datanames,
transformators = transformators,
ui_args = ui_args,
server_args = server_args
)
attr(ans, "teal_bookmarkable") <- bk
ans
}
dummy_transformator <- teal_transform_module(
label = "Dummy Transform",
ui = function(id) div("(does nothing)"),
server = function(id, data) {
moduleServer(id, function(input, output, session) data)
}
)
plot_transformator <- teal_transform_module(
label = "Plot Settings",
ui = function(id) div("(does nothing)"),
server = function(id, data) {
moduleServer(id, function(input, output, session) data)
}
)
static_decorator <- teal_transform_module(
label = "Static decorator",
server = function(id, data) {
moduleServer(id, function(input, output, session) {
reactive({
req(data())
within(data(), {
plot <- plot +
ggtitle("This is title") +
xlab("x axis")
})
})
})
}
)
complete_modules <- modules(
custom_module(
label = "Data Overview",
datanames = c("ADSL", "ADAE", "ADVS"),
ui_args = list(
view_type = "table",
page_size = 10,
filters = c("ARM", "SEX", "RACE"),
decorators = list(static_decorator)
),
server_args = list(
cache = TRUE,
debounce = 1000,
decorators = list(static_decorator)
),
transformators = list(dummy_transformator),
bk = TRUE
),
modules(
label = "Nested 1",
custom_module(
label = "Interactive Plots",
datanames = c("ADSL", "ADVS"),
ui_args = list(
plot_type = c("scatter", "box", "line"),
height = 600,
width = 800,
color_scheme = "viridis"
),
server_args = list(
render_type = "svg",
cache_plots = TRUE
),
transformators = list(dummy_transformator, plot_transformator),
bk = TRUE
),
modules(
label = "Nested 2",
custom_module(
label = "Summary Statistics",
datanames = "ADSL",
ui_args = list(
stats = c("mean", "median", "sd", "range"),
grouping = c("ARM", "SEX")
)
),
modules(
label = "Labeled nested modules",
custom_module(
label = "Subgroup Analysis",
datanames = c("ADSL", "ADAE"),
ui_args = list(
subgroups = c("AGE", "SEX", "RACE"),
analysis_type = "stratified"
),
bk = TRUE
)
),
modules(custom_module(label = "Subgroup Analysis in non-labled modules"))
)
),
custom_module("Non-nested module")
)
cat(format(complete_modules))
cat(format(complete_modules, what = c("ui_args", "server_args", "transformators")))
cat(format(complete_modules, what = c("decorators", "transformators")))
Filter settings for teal applications
Description
Specify initial filter states and filtering settings for a teal app.
Usage
teal_slices(
...,
exclude_varnames = NULL,
include_varnames = NULL,
count_type = NULL,
allow_add = TRUE,
module_specific = FALSE,
mapping,
app_id = NULL
)
as.teal_slices(x)
## S3 method for class 'teal_slices'
c(...)
Arguments
... |
any number of |
include_varnames, exclude_varnames |
( |
count_type |
This is a new feature. Do kindly share your opinions on
(
|
allow_add |
( |
module_specific |
(
|
mapping |
(named
|
app_id |
( |
x |
( |
Details
Produces a teal_slices object.
The teal_slice components will specify filter states that will be active when the app starts.
Attributes (created with the named arguments) will configure the way the app applies filters.
See argument descriptions for details.
Value
A teal_slices object.
Examples in Shinylive
- example-1
See Also
teal.slice::teal_slices, teal.slice::teal_slice, slices_store()
Examples
filter <- teal_slices(
teal_slice(dataname = "iris", varname = "Species", id = "species"),
teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),
teal_slice(
dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"
),
teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),
mapping = list(
module1 = c("species", "sepal_length"),
module2 = c("mtcars_mpg"),
global_filters = "long_petals"
)
)
app <- init(
data = teal_data(iris = iris, mtcars = mtcars),
modules = list(
module("module1"),
module("module2")
),
filter = filter
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
Data module for teal transformations and output customization
Description
teal_transform_module provides a shiny module that enables data transformations within a teal application
and allows for customization of outputs generated by modules.
Usage
teal_transform_module(
ui = NULL,
server = function(id, data) data,
label = "transform module",
datanames = "all"
)
Arguments
ui |
( |
server |
( |
label |
( |
datanames |
( |
Transforming Module Inputs in teal
Data transformations occur after data has been filtered in teal.
The transformed data is then passed to the server of teal_module() and managed by teal's internal processes.
The primary advantage of teal_transform_module over custom modules is in its error handling, where all warnings and
errors are managed by teal, allowing developers to focus on transformation logic.
For more details, see the vignette: vignette("transform-input-data", package = "teal").
Customizing Module Outputs
teal_transform_module also allows developers to modify any object created within teal.data::teal_data.
This means you can use it to customize not only datasets but also tables, listings, and graphs.
Some teal_modules permit developers to inject custom shiny modules to enhance displayed outputs.
To manage these decorators within your module, use ui_transform_teal_data() and srv_transform_teal_data().
(For further guidance on managing decorators, refer to ui_args and srv_args in the vignette documentation.)
See the vignette vignette("transform-module-output", package = "teal") for additional examples.
server as a language
The server function in teal_transform_module must return a reactive teal.data::teal_data object.
For simple transformations without complex reactivity, the server function might look like this:s
function(id, data) {
moduleServer(id, function(input, output, session) {
reactive({
within(
data(),
expr = x <- subset(x, col == level),
level = input$level
)
})
})
}
The example above can be simplified using make_teal_transform_server, where level is automatically matched to the
corresponding input parameter:
make_teal_transform_server(expr = expression(x <- subset(x, col == level)))
Examples in Shinylive
- example-1
Examples
data_transformators <- list(
teal_transform_module(
label = "Static transformator for iris",
datanames = "iris",
server = function(id, data) {
moduleServer(id, function(input, output, session) {
reactive({
within(data(), {
iris <- head(iris, 5)
})
})
})
}
),
teal_transform_module(
label = "Interactive transformator for iris",
datanames = "iris",
ui = function(id) {
ns <- NS(id)
tags$div(
numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1)
)
},
server = function(id, data) {
moduleServer(id, function(input, output, session) {
reactive({
within(data(),
{
iris <- iris[, 1:n_cols]
},
n_cols = input$n_cols
)
})
})
}
)
)
output_decorator <- teal_transform_module(
server = make_teal_transform_server(
expression(
object <- rev(object)
)
)
)
app <- init(
data = teal_data(iris = iris),
modules = example_module(
transformators = data_transformators,
decorators = list(output_decorator)
)
)
if (interactive()) {
shinyApp(app$ui, app$server)
}
Function for validating the title parameter of teal::init
Description
Checks if the input of the title from teal::init will create a valid title and favicon tag.
Usage
validate_app_title_tag(shiny_tag)
Arguments
shiny_tag |
( |
Validate that dataset has a minimum number of observations
Description
This function is a wrapper for shiny::validate.
Usage
validate_has_data(
x,
min_nrow = NULL,
complete = FALSE,
allow_inf = TRUE,
msg = NULL
)
Arguments
x |
( |
min_nrow |
( |
complete |
( |
allow_inf |
( |
msg |
( |
Examples in Shinylive
- example-1
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 for shiny::validate.
Usage
validate_has_elements(x, msg)
Arguments
x |
vector |
msg |
message to display |
Examples in Shinylive
- example-1
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 for shiny::validate.
Usage
validate_has_variable(data, varname, msg)
Arguments
data |
( |
varname |
( |
msg |
( |
Examples in Shinylive
- example-1
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 for shiny::validate.
Usage
validate_in(x, choices, msg)
Arguments
x |
Vector of values to test. |
choices |
Vector to test against. |
msg |
( |
Examples in Shinylive
- example-1
Examples
ui <- fluidPage(
selectInput(
"species",
"Select species",
choices = c("setosa", "versicolor", "virginica", "unknown species"),
selected = "setosa",
multiple = FALSE
),
verbatimTextOutput("summary")
)
server <- function(input, output) {
output$summary <- renderPrint({
validate_in(input$species, iris$Species, "Species does not exist.")
nrow(iris[iris$Species == input$species, ])
})
}
if (interactive()) {
shinyApp(ui, server)
}
Send input validation messages to output
Description
Captures messages from InputValidator objects and collates them
into one message passed to validate.
Usage
validate_inputs(..., header = "Some inputs require attention")
Arguments
... |
either any number of |
header |
( |
Details
shiny::validate is used to withhold rendering of an output element until
certain conditions are met and to print a validation message in place
of the output element.
shinyvalidate::InputValidator allows to validate input elements
and to display specific messages in their respective input widgets.
validate_inputs provides a hybrid solution.
Given an InputValidator object, messages corresponding to inputs that fail validation
are extracted and placed in one validation message that is passed to a validate/need call.
This way the input validator messages are repeated in the output.
The ... argument accepts any number of InputValidator objects
or a nested list of such objects.
If validators are passed directly, all their messages are printed together
under one (optional) header message specified by header. If a list is passed,
messages are grouped by validator. The list's names are used as headers
for their respective message groups.
If neither of the nested list elements is named, a header message is taken from header.
Value
Returns NULL if the final validation call passes and a shiny.silent.error if it fails.
Examples in Shinylive
- example-1
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 of x is less than min_levels
or greater than max_levels the validation will fail.
This function is a wrapper for shiny::validate.
Usage
validate_n_levels(x, min_levels = 1, max_levels = 12, var_name)
Arguments
x |
variable name. If |
min_levels |
cutoff for minimum number of levels of |
max_levels |
cutoff for maximum number of levels of |
var_name |
name of variable being validated for use in validation message |
Examples in Shinylive
- example-1
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 for shiny::validate.
Usage
validate_no_intersection(x, y, msg)
Arguments
x |
vector |
y |
vector |
msg |
( |
Examples in Shinylive
- example-1
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 for shiny::validate.
Usage
validate_one_row_per_id(x, key = c("USUBJID", "STUDYID"))
Arguments
x |
( |
key |
( |
Examples in Shinylive
- example-1
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)
}