如何在 R Shiny 应用程序中使相关的服务器端选择 UI 元素?

How to make related server-side selectize UI elements in R Shiny application?

我有一个带有两个 UI 选择器的 R Shiny 应用程序,每个选择器都有一个很大的项目列表。我知道如何为一个元素制作服务器端元素。但是如何使两个相关的服务器端 'selectInput' 元素。因此,当一个元素发生变化时 - 另一个元素应适当反映。

示例。

  1. 第一个列表有 97,310 个元素。

  2. 第二个列表应该有:

2.1。对于第一个元素 "Aaban" - 2 个相关值 (10, 11)

2.2。对于第二个元素 "Aabha" - 1 个相关值 (12)

2.3。对于第三个元素 "Aabid" - 3 个相关值 (13, 14, 15)

这是R代码。

library(shiny)
library(dplyr)
library(babynames)

# 1. Data sets

# 1.1. First data set (list)
list_names <- babynames::babynames %>% 
  distinct(name) %>%
  pull(name) %>%
  sort()

# 1.2. Second data set (data frame) for 3 first 'names' elements
df_ages <- data.frame(
  name = c("Aaban", "Aaban", "Aabha", "Aabid", "Aabid", "Aabid"),
  age  = c(10, 11, 12, 13, 14, 15))

# 2. UI
ui <- fluidPage(
  fluidRow(selectInput("si_name", "Name", multiple = FALSE, choices = character(0))),
  fluidRow(selectInput("si_age", "Age", multiple = FALSE, choices = character(0))))

# 3. Server
server <- function(input, output, session) {
  updateSelectizeInput(session, "si_name", choices = list_names, server = TRUE)
  updateSelectizeInput(session, "si_age", choices = df_ages$age, server = TRUE)
}

# 4. App
shinyApp(ui, server)

谢谢!

我想你想要:

# 2. UI
ui <- fluidPage(
  fluidRow(selectInput("si_name", "Name", multiple = FALSE, 
                       choices = unique(df_ages$name))),
  fluidRow(selectInput("si_age", "Age", multiple = FALSE, choices = character(0)))
)

# 3. Server
server <- function(input, output, session) {

  observeEvent(input$si_name, {
    ages <- df_ages[df_ages$name == input$si_name, "age"]
    updateSelectizeInput(session, "si_age", choices = ages, server = TRUE)
  })

}