简体   繁体   English

在 shiny 中使用带有 null 值的 observeEvent

[英]Using observeEvent in shiny with null values

I'm struggling with a reactive shiny question and was hoping to get some help.我正在努力解决一个反应性的 shiny 问题,并希望能得到一些帮助。 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?我将如何修改此代码以允许在某些字段中选择 null 并让其他选项对此完全反应? Right now its only reactive when you select every field from top to bottom.现在,当您从上到下的每个字段 select 时,它唯一的反应。 I want it to be responsive to null values and have order not matter.我希望它能够响应 null 值并且顺序无关紧要。

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.我可以在查询时使用复杂的情况来做到这一点,但我的实际数据集有大约 10 个不同的输入,并且通过扩展大量不同的组合,所以这样做来处理每个可能的组合是不可行的。

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



?observeEvent

This was a recent discovery for me too这对我来说也是最近的发现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM