selectInput R Shiny 中的动态组数

dynamic number of groups in selectInput R Shiny

我需要帮助完成一项任务。我有数据框:

df <- data.frame(
  UserGroup = c("UserGroup1", "UserGroup2", "UserGroup2", "UserGroup3", "UserGroup3", "UserGroup3", NA, NA, NA, NA),
  User = c("User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10")
)

我想获得如下图所示的 selectInput 版本。

我找到了代码:

    selectInput("state", "Choose a state:",
       list(
          `East Coast` = list("NY", "NJ", "CT"),
          `West Coast` = list("WA", "OR", "CA"),
          `Midwest` = list("MN", "WI", "IA") 
       )
    )

手动做起来很容易,但问题是df是一个来自数据库的数据框,它可以包含随机数量的组和用户。 有谁知道selectInput的代码怎么写,或者之前准备数据怎么自动达到预期的效果吗?

所述,您可以使用split()。显然,当一个组包含单个观察值时效果不佳,因此我添加了 User1 bis 来向您展示。此外,您需要为组为 NA 的用户创建一个类别(我将 "Without group" 放在这里,以便它按字母顺序排列在输入列表的末尾)。

library(shiny)
library(dplyr)

df <- data.frame(
  UserGroup = c("UserGroup1", "UserGroup1", "UserGroup2", "UserGroup2", "UserGroup3", "UserGroup3", "UserGroup3", NA, NA, NA, NA),
  User = c("User1", "User1 bis", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10")
)

df_2 <- df %>%
  mutate(UserGroup = ifelse(is.na(UserGroup), "Without Group", UserGroup)) 

ui <- fluidPage(
  selectInput("state", "Choose a state:",
              choices = split(df_2$User, df_2$UserGroup),
              selected = "User 1"
  )

)

server <- function(input, output, session) {}

shinyApp(ui, server)