基于单选按钮的 selectizeInput 的闪亮更新选择

Shiny update choices of selectizeInput based on radio buttons

我正在尝试根据用户是单击“通用名称”还是“学名”按钮来更新 selectizeInput() 中的选项。默认为“通用名称”。

我从 知道 conditionalPanel(),但我的选择会 link 到输出图,所以我需要它们是反应性的。因此,单击“学名”后,我希望清除当前选项,然后仅可以选择新选项 (names_vector2)。同样,如果用户随后单击返回“通用名称”,我希望清除当前选项,并且只有 names_vector1 中的选项可供选择。

希望这是有道理的!

library(shiny)
library(shinyWidgets)

names_vector1 = paste0("common", 1:10)
names_vector2 = paste0("scientific", 1:10)

ui = fluidPage(
  fluidRow(
    selectizeInput(
      inputId = "species_selector",
      label = "Choose a species:",
      selected = "common1",
      choices = c("Choose" = "", names_vector1),
      options = list(
        maxOptions = 5,
        maxItems = 4
      )
    ),
    awesomeRadio(
      inputId = "species_selector_type",
      label = NULL,
      choices = c("Common name","Scientific name"),
      selected = "Common name",
      inline = TRUE
    )
  )
)

server = server = server = function(input, output, session){
 
  # I want to change the selectizeInput choices as the user clicks the buttons:
  # "Common name" and "Scientific name"
  observeEvent(input$species_selector_type {
    
    if (input$species_selector_type == "Scientific name")
    updateSelectizeInput(
      session,
      inputId = "species_selection",
      choices = c("Choose" = "", names_vectors),
    )
  })
  # The desired result is to:
  # 1. Clear the current selectiveInput selected names each time a new button is clicked
  # 2. Update the choices so that:
        # Common name = names_vector1
        # Scientific name = names_vector2
}

shinyApp(ui, server)

您快完成了 - 添加了一个 else if 语句:

library(shiny)
library(shinyWidgets)

names_vector1 = paste0("common", 1:10)
names_vector2 = paste0("scientific", 1:10)

ui = fluidPage(fluidRow(
  selectizeInput(
    inputId = "species_selector",
    label = "Choose a species:",
    selected = "common1",
    choices = c("Choose" = "", names_vector1),
    options = list(maxOptions = 5,
                   maxItems = 4)
  ),
  awesomeRadio(
    inputId = "species_selector_type",
    label = NULL,
    choices = c("Common name", "Scientific name"),
    selected = "Common name",
    inline = TRUE
  )
))

server = server = server = function(input, output, session) {
  observeEvent(input$species_selector_type, {
    if (input$species_selector_type == "Common name") {
      updateSelectizeInput(session,
                           inputId = "species_selector",
                           choices = c("Choose" = "", names_vector1))
    } else if (input$species_selector_type == "Scientific name") {
      updateSelectizeInput(session,
                           inputId = "species_selector",
                           choices = c("Choose" = "", names_vector2))
    }
  })
}

shinyApp(ui, server)