【问题标题】:Dynamic user interface with r带有 r 的动态用户界面
【发布时间】:2021-07-03 20:37:05
【问题描述】:

我想创建一个动态用户界面。当我选择"Total" 时,我不想显示任何内容,甚至是一个空框架。我希望仅在选择 "Cancer"" without cancer" 时显示某些内容。

ui<-fluidPage(
  titlePanel("Dynamically generated user interface components"),
  fluidRow(
    
    column(3, wellPanel(
      selectInput("input_type", "Input type",
                  c("Total","Cancer", "Without cancer"
                  )
      )
    )),
    
    column(3, wellPanel(
      # This outputs the dynamic UI component
      uiOutput("ui")
    ))
  )
)







server<-function(input, output) {
  
  output$ui <- renderUI({
    if (is.null(input$input_type))
      return()
    
    # Depending on input$input_type, we'll generate a different
    # UI component and send it to the client.
    switch(input$input_type,
           "Cancer" = selectInput("dynamic", "Dynamic",
                                  choices = c("Lung cancer" = "Lung cancer",
                                              "Breast cancer" = "Breast cancer",
                                              "Colon cancer"=  "Colon cancer"),),
           "Without cancer" = selectInput("dynamic", "Dynamic",
                                  choices = c("Pneumonia" = "Pneumonia",
                                              "Gastro-enteritis" = "Gastro-enteritis",
                                              "Flu"=  "Flu"),)
    )
  })
  
  output$input_type_text <- renderText({
    input$input_type
  })
  
  output$dynamic_value <- renderPrint({
    str(input$dynamic)
  })
  
}

shinyApp(ui,server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以使用shinyjs::toggle() 隐藏和显示带有条件的元素。

    首先添加{shinyjs},从ui 中调用useShinyjs(),然后在需要隐藏和显示的wellPanel 中添加id

    library(shiny)
    library(shinyjs)
    ui<-fluidPage(
      useShinyjs(),
      titlePanel("Dynamically generated user interface components"),
      fluidRow(
        
        column(3, wellPanel(
          selectInput("input_type", "Input type",
                      c("Total","Cancer", "Without cancer"
                      )))),
        
        column(3, wellPanel( 
          id="wp",
          uiOutput("ui")
        ))
      )
    )
    

    然后添加一个observe() 来触发toggle() wellPanel 无论何时input$input_type == "Total"

    server<-function(input, output) {
      observe(toggle(id = "wp", condition = input$input_type != "Total"))
      ...
    

    您也可以选择将if() 替换为req()

      output$ui <- renderUI({
        req( input$input_type != "Total")
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      相关资源
      最近更新 更多