Shiny:在选择另一个selectInput的值后创建一个selectInput

时间:2017-05-19 16:49:50

标签: r shiny reactive

我有一个闪亮的应用程序,我想在数据框上构建一个条件查询系统。

首先,我想让selectInput显示所有可用的表。在用户选择了一个表之后,我想要另一个框出现在他可以选择要过滤的列名的位置。这就是我现在所拥有的:

ui.r:

library(shiny)
library(shinydashboard)

source("global_variables.r")

ui=dashboardPage(

  dashboardHeader(title="Test"),
  dashboardSidebar(

    sidebarMenu(

      menuItem("Conditionals",tabName = "conditionals")

    )

  ),
  dashboardBody(

    tabItems(

      tabItem(tabName="conditionals",
              fluidRow(

                box(

                  title = "Conditionals",
                  width = 4,
                  selectInput("Con_tableName",choices=c("NONE",tableNames),label = "Table Name"),
                  tags$div(id = 'placeholder') 


                )

              )

      )

    )

  )

)

server.r:

library(shiny)

source("global_variables.r", local = FALSE)

Table1=data.frame();

shinyServer(
  function(input, output,session) {



    observe({
      reactive(
        if(input$Con_tableName!="NONE"){

          insertUI( selector="#placeholder",
                    ui={
                      selectInput("Con_colName",choices=c("NONE",colnames(dynGet(input$Con_tableName))),label = "Column Name")
                    }
          )
        }
      )
    })
  }
)

global_variables.r:

tableNames=c("Table1","Table2","Table3")

问题是,如果我在selectInput中选择一个值,则观察不会被触发。

编辑: 根据BigDataScientists评论,将insertUI更改为renderUI。更新文件:

ui.r:

library(shiny)
library(shinydashboard)

source("global_variables.r")

ui=dashboardPage(

  dashboardHeader(title="Test"),
  dashboardSidebar(

    sidebarMenu(

      menuItem("Conditionals",tabName = "conditionals")

    )

  ),
  dashboardBody(

    tabItems(

      tabItem(tabName="conditionals",
              fluidRow(

                box(

                  title = "Conditionals",
                  width = 4,
                  selectInput("Con_tableName",choices=c("NONE",tableNames),label = "Table Name"),
                  uiOutput("conditionalUI")


                )

              )
      )

    )

  )
)

server.r:

library(shiny)

source("global_variables.r", local = FALSE)

Table1=data.frame();

shinyServer(
  function(input, output,session) {



    observeEvent(input$Con_tableName,{
      reactive(
        if(input$Con_tableName!="NONE"){

          output$conditionalUI=renderUI({

           selectInput("Con_colName",choices=c("NONE",colnames(input$Con_tableName)),label = "Column Name")

          })

        }
      )
    })
  }
)

1 个答案:

答案 0 :(得分:2)

您可以使用conditionalPanel()。下面有一个小例子可能适用于您的情况。

library(shiny)

shinyApp(
  ui <- fluidPage(
    mainPanel(
      selectInput("input1", "Select something", choices = c('','1','2','3')),
      conditionalPanel("input.input1!=''",
                       selectInput('input2', "Select something else", choices = c('4','5')))
    )
  ),
  server <- function(input, output){}
)