Home > OS >  How to make one of the filter functions conditional in a reactive function for a shiny flexdashboard
How to make one of the filter functions conditional in a reactive function for a shiny flexdashboard

Time:10-23

I have a dataset and am building a shiny flexdashboard with multiple user inputs which filter the data down to a subset. I am struggling with just one of the filters, where if the user chooses 'ALL' in selectInput, I want that filter function not to do anything and just return the data as is. Below is one of my attempts:

library(flexdashboard)
library(DT)
library(lubridate)
library(readr)
library(tidyverse)
...
qry <- read_file("some_query.sql")
Data_df  <- con %>% tbl(sql(qry)) %>% collect()
doctors_to_choose <- unique(pull(Data_df, 'Doctor')) %>%append('ALL')


Column {data-width=200 .sidebar}
-----------------------------------------------------------------------

```{r}
checkboxGroupInput("drug_classes",
  label = "Choose the classes of drugs",
  choices = c("II", "III", "IV", "V"),
  selected = c("V"),
)


selectInput(
  inputId="chosen_doctor",
  label="Choose Doctor",
  choices=doctors_to_choose,
  selected = "ALL",
  multiple = FALSE,
  size = NULL
)


show_data_df <- reactive({
  Data_df %>% 
filter(`Drug Class` %in% input$drug_classes) %>%
 {if (input$chosen_doctor != "ALL") filter(Doctor == input$chosen_doctor ) 
else filter(`Drug Class` %in% input$drug_classes) }
} )
``` 

I tried to use an if-else statement as above but failed. because In the original code, I have a long list of filters applied so ideally I would like to use something that does not require me to retype all the previous filters/actions like I did in the else part above.

CodePudding user response:

One option is to use purrr::when to apply a case_when like statement within the pipe logic for data.frames:

library(dplyr)
library(purrr)

Data_df %>% 
  filter(`Drug Class` %in% input$drug_classes) %>% 
  when(input$chosen_doctor != "ALL" ~ filter(., Doctor == input$chosen_doctor),
       TRUE                         ~ filter(., `Drug Class` %in% input$drug_classes))
  • Related