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

时间:2019-05-07 16:50:36

标签: r shiny r-markdown flexdashboard

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

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()

2 个答案:

答案 0 :(得分:1)

您可以使用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)

答案 1 :(得分:0)

我进一步研究了这篇文章: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值。否则,代码将崩溃。

请注意,我在data.table上为dt着迷。