【问题标题】:How to do nested selections selectInput() in RMarkdown with Shiny?如何在 RMarkdown 中使用 Shiny 进行嵌套选择 selectInput()?
【发布时间】:2019-09-25 09:18:38
【问题描述】:

在我的 RMarkdown \ flexdashboard 代码和 shiny 的下面代码的 sn-p 中,我需要修改 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() 中封装代码没有帮助:

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

【问题讨论】:

标签: r shiny r-markdown flexdashboard


【解决方案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)

【讨论】:

  • 它在 RMarkdown 文档中应该可以正常工作,只需确保在 YAML 标头中指定 runtime:shiny
【解决方案2】:

我进一步研究了这篇文章: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

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 2020-12-09
    • 2019-01-19
    • 2018-06-14
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多