SummaryWidget reports summary statistics for a data set linked with Crosstalk-compatible HTML widgets within an R Markdown page or Shiny app.

To begin, install the summarywidget and crosstalk packages:

devtools::install_github("kent37/summarywidget")
devtools::install_github("rstudio/crosstalk")

The crosstalk package includes widgets which control selection within a dataset. You may also want to use other Crosstalk-compatible widgets; the Crosstalk documentation has a list. To keep this guide simple, it uses a single crosstalk::filter_checkbox for selection.

 

Crosstalk links widgets through an instance of crosstalk::SharedData. Here, we share the mtcars data set.

library(crosstalk)

shared_mtcars = SharedData$new(mtcars)
 

A crosstalk::filter_checkbox allows selection from a categorical variable such as the Cylinders column of the shared_mtcars data.

filter_checkbox("cyl", "Cylinders", shared_mtcars, ~cyl, inline = TRUE)

Create a summarywidget with a reference to the shared data. The summarywidget default statistic is a simple count of selected items. Click the checkboxes above to see the count change below.

library(summarywidget)

summarywidget(shared_mtcars)
 

A summarywidget can display a count, arithmetic mean or sum. To display a sum or mean you must also specify the column to summarize. Here we show the mean MPG for the selected cars. The digits parameter controls the number of decimal digits displayed.

summarywidget(shared_mtcars, statistic='mean', column='mpg', digits=1)
 

You can also apply a filter to the initial data set and display a summary restricted to the filtered data. Here we show the count of selected cars with automatic transmission.

summarywidget(shared_mtcars, selection=~am==0)
 

Putting it all together, this example shows the average MPG for selected cars with automatic transmission.

summarywidget(shared_mtcars, 'mean', 'mpg', selection=~am==0, digits=1)
 

The output of summarywidget is enclosed in a <span> tag so you can use it inline in text. See the Introduction for an example.