R shiny - 使用其中任何一个选项的SelectizeInput

时间:2017-02-04 22:39:36

标签: r shiny

我有selectizeInput,其中有6个选项:A1,A2,B1,B2,C1,C2。

现在我有以下代码:

ui <- fluidPage(
  selectizeInput("select", "Select multiple", multiple = T, 
                 choices = c("A1", "A2", "B1", "B2", "C1", "C2"))

它产生了这个:

select

如果你想要一个可重复的最小例子,那么这里有一个闪亮的应用程序。

library(shiny)

ui <- fluidPage(
  selectizeInput("select", "Select multiple", multiple = T, 
                 choices = c("A1", "A2", "B1", "B2", "C1", "C2"))
)

server <- function(input, output){}
shinyApp(ui, server)

但我想要的是每种类型的字母中只有一种可供选择

A1,B1,C2,很好,但A1,A2不是。换句话说,A1和A2属于一组,B1和B2属于一组等,每组只能选择一个。

有两种方法可以使用此功能。

  1. 选择A1后,A2将从其余选项中消失。用户必须删除A1才能在其余选项中获得A2(和A1)
  2. 选择A1后,A2仍然在其余选项中,但如果选择A2,则取消选择A1并返回其余选项
  3. 有没有办法用updateSelectizeInput

    执行此操作

1 个答案:

答案 0 :(得分:2)

我认为排除部分可以由一些专家在这里做得更漂亮=)关于闪亮的部分,它应该符合您的要求。

library(shiny)

ui <- fluidPage(
  uiOutput("select")
)

server <- function(input, output, session){
  global <- reactiveValues(choices = c("A1", "A2", "B1", "B2", "C1", "C2"))
  output$select <-  renderUI({
    selectizeInput("select", "Select multiple", multiple = T, choices = global$choices)
  })

  observe({
    if(!is.null(input$select)){
      # exclude by comparing first Letters
      firstLetterSelected <- as.character(sapply(input$select, substr, 1, 1))
      firstLetterAllChoices <- as.character(sapply(global$choices, substr, 1, 1))
      subset <- sort(c(input$select, global$choices[which(!(firstLetterAllChoices %in% firstLetterSelected))]))
      updateSelectizeInput(session, "select", choices = subset, selected = input$select)
    }else{
      # if inputs are erased completely this list is not refreshed without this else statement
      updateSelectizeInput(session, "select", choices = global$choices, selected = input$select)
    }
  })
}
shinyApp(ui, server)