如何使用 Shiny 在 RMarkdown 中进行嵌套选择 selectInput()?

How to do nested selections selectInput() in RMarkdown with Shiny?

在我的 RMarkdown \ flexdashboard 代码 shiny 下面的一段代码中,我需要修改第二个 selectInput()choices函数,基于在第一个 selectInput() 函数中所做的选择。

selectInput('theme', 'Select theme:',
            choices = c(dtThemes$Theme %>% unique()))  

selectInput('question', 'Select Question:', 
            choices = c(dtQuestions$Question %>% unique())) # This works
            #choices = strQuestions)  # This does not work

strQuestions <- reactive({
    nQuestions <- dtThemes[Theme == input$theme, Q2018]
    dtQuestions[nQuestion %in% nQuestions, strQuestion]
})

我该怎么做?

renderUI()中封装代码没有帮助:

  renderUI({
    selectInput('question', 'Select Question:', 
                strQuestions(), width="100%") 
  })

您可以使用 updateSelectInput。下面是一个小例子,其中选项 B 的选择是选项 A 中指定长度的序列:

library(shiny)

ui <- fluidPage(
   selectInput("A", "Option A", choices = 1:10),
   selectInput("B", "Option B", choices = NULL)
)


server <- function(input, output, session) {
   observe({
      choices_B <- seq(as.numeric(input$A))
      updateSelectInput(session, "B", choices = choices_B)
   })
}


shinyApp(ui, server)

我进一步研究了这个 post:Create reactive selectInput - flexdashboard with Shiny 并且能够弄清楚如何使我的代码工作:

selectInput('theme', 'Select theme:',
            choices = c("All", dt$Theme %>% unique()), selected="All")

dt.subset<- reactive({
    if (input$theme=="All") {
      dt
    }else{
      dt[Theme == input$theme]
    }
  })
 renderUI({
    selectInput('question', 'Select Question:', 
                choices = (dt.subset()$Question ) %>% unique(), 
                selected =  ( (dt.subset()$Question ) %>% unique() )[1]) 
  })

}

诀窍是您需要有一个默认值 selected。否则,代码会崩溃。

另请注意,我正在为 dt 考虑 data.table