Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using observeEvent in shiny with null values

Tags:

r

shiny

I'm struggling with a reactive shiny question and was hoping to get some help. Lets say I have a very simple app which displays the mean altitude given a series of selections:

library(tidyverse)
library(shiny)
library(DT)

df <- data.frame(cat = sample(LETTERS[1:4], 20, replace = T),
                 city = sample(c("Tokyo", "Madrid", "Paris"), 20, replace = T),
                 pop = sample(1:7, 20, replace = T),
                 altitude = sample(10000:15000, 20, replace = F))

ui <- fluidPage(
  selectizeInput("cat", "Category:",
                 choices = c("A", "B", "C", "D"),
                 multiple = T,
                 selected = "A"),
  selectizeInput("city","City:", 
                 choices = NULL, 
                 multiple = T),
  selectizeInput("pop","Population:", 
                 choices = NULL, 
                 multiple = T),
  dataTableOutput("table")
)

server <- function(input, output, session) {
  observeEvent(input$cat,{
    updateSelectInput(session,"city",
                      choices = df %>% filter(cat == input$cat) %>%
                        .$city %>% unique,
                      selected = "")
  })
  observeEvent(input$city,{
    updateSelectInput(session,"pop",
                      choices = df %>% filter(cat == input$cat & city == input$city) %>%
                        .$pop %>% unique,
                      selected = "")
  })
  output$table <- renderDataTable({
    df %>%
      filter(cat == input$cat, city == input$city, pop == input$pop %>% as.numeric) %>%
      summarise(mean_altitude = mean(altitude))
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

How would I modify this code to allow for null selections in certain fields and have the other options be completely reactive to this? Right now its only reactive when you select every field from top to bottom. I want it to be responsive to null values and have order not matter.

I can do this using complex case when queries, but my actual data set has approximately 10 different inputs, and by extension tons of different combinations, so doing this to deal with every possible combo isn't feasible.

like image 746
DJC Avatar asked Dec 06 '25 14:12

DJC


1 Answers

observeEvent(input$id, {
    code 
    ...
}, ignoreNULL = FALSE)



?observeEvent

This was a recent discovery for me too

like image 186
Carl Boneri Avatar answered Dec 09 '25 02:12

Carl Boneri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!