Search code examples
rshinyr-markdownflexdashboard

Use values of a vector as input for flexdashboards


I'm writing an interactive document with shiny and flexdashboard and would like to select values from a vector (or column) as input to filter the dataset. Consider the example below:

---
title: "Example"
runtime: shiny
theme: simplex
vertical_layout: fill
output:
  flexdashboard::flex_dashboard:
  orientation: rows
---

```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
library(DT)
```

Sidebar {.sidebar}
======================

### Filtering options

```{r echo = FALSE}
selectInput("ncyl",
        label = "Value of cyl:",
        choices = mtcars %>% .$cyl %>% unique %>% sort,
        selected = 20)

```

Explore
======================

Row
----------------------

### Table

```{r echo = FALSE}
DT::renderDataTable({
  mtcars %>%
    dplyr::filter(cyl==input$ncyl) %>% 
    dplyr::select(cyl, disp) %>% 
    dplyr::arrange(-disp) %>% 
    DT::datatable(options = list(
      pageLength = 10,
      bPaginate = TRUE,
      scrollX = TRUE,
      sScrollY = '75vh',
      scrollCollapse = TRUE),
      extensions = list("Scroller")
    )})
```

In this case example, a tab allows to select one of the three possible values of column cyl to filter the dataset.

I would like to replace this by a number of buttons where I can select of many of these values to select (eg. in this case there would be three buttons, for values 4, 6 and 8), so that all or some of these values are used to filter, but not necessarily only one. This is intended to be used for a column with a potentially large number of values, so a scroll bar might be necessary for this.

Is it possible to achieve this with flexdashboard? So far, I haven't been able to find an example for this in the Rmarkdown gallery.


Solution

  • You can edit the settings for the dropdown box to allow multiple selections.

    selectInput("ncyl",
            label = "Value of cyl:",
            choices = mtcars %>% .$cyl %>% unique %>% sort,
            multiple = T)
    

    You will also need to edit the server codes according to the fact that your selection is now a list & not a value.

    mtcars %>%
        dplyr::filter(cyl%in%input$ncyl) %>%