代码之家  ›  专栏  ›  技术社区  ›  frank

根据R中的另一个selectInput值更改默认值

  •  0
  • frank  · 技术社区  · 7 年前

    我想要两个闪亮的输入。第一个选项有一个默认为“a”的选项。我希望第二个输入值基于第一个输入值设置为默认值。即,如果第一个选择是A,则第二个选择的默认值为“低”,如果第一个选择是C或D,则第二个选择的默认值为“高”。我需要将第二个输入选项更改为任何内容。

    正如我的代码所示,我目前正在使用带有uiOutput的selectInput将其链接在一起。目前,第二个值的默认值始终为“低”,即使在我选择C或D时也是如此。我希望能够选择C,并将第二个选择的默认值设置为“高”

    我的代码:

    df=data.frame(expand.grid(col1=LETTERS[1:4],col2=c('LOW','MEDIUM','HIGH')))
    
    ui = fluidPage(
      column(4,
             selectInput('d1','Drop 1',
                         choices = sort(unique(df$col1)),
                         selected = sort(df$col1)[1]),
             uiOutput("secondSelection")
      )
    )
    
    server <- function(input, output, session) {
      output$secondSelection = renderUI({
        selectInput("User", "Value Dependent on Drop 1:", 
                    choices = as.character(df[df$col1==input$d1,"col2"]))
      }) 
    }
    
    shinyApp(ui, server)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   frank    7 年前

    我找到了一个名为updateselectinput的函数,并添加了它来解决这个问题

    df=data.frame(expand.grid(col1=LETTERS[1:4],col2=c('LOW','MEDIUM','HIGH')))
    
    ui = fluidPage(
      column(4,
             selectInput('d1','Drop 1',
                         choices = sort(unique(df$col1)),
                         selected = sort(df$col1)[1]),
             selectInput('d2','Drop 2',
                         choices = sort(unique(df$col2))
                         )
      )
    )
    
    server <- function(input, output, session) {
    
      observe({
        x = input$d1
    
        if(x=='A'){
          updateSelectInput(session,'d2',
                            choices = sort(unique(df$col2)),
                            selected = 'LOW')
        }else if(x=='C' || x=='D'){
          updateSelectInput(session,'d2',
                            choices = sort(unique(df$col2)),
                            selected = 'HIGH')
        }else{
          updateSelectInput(session,'d2',
                            choices = sort(unique(df$col2)),
                            selected = 'MEDIUM')
        }
    
      })
    
    }
    
    shinyApp(ui, server)
    
    推荐文章