Reputation: 375
I need help in one task. I have dataframe:
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")
)
I would like to get version of selectInput like on the picture below.
I found the code:
selectInput("state", "Choose a state:",
list(
`East Coast` = list("NY", "NJ", "CT"),
`West Coast` = list("WA", "OR", "CA"),
`Midwest` = list("MN", "WI", "IA")
)
)
It is easy to do it manually, but the problem is that df is a data frame come from database and it can contain random number of groups and users. Does anyone have idea how to write code of selectInput or how to prepare data before to get expected effect automatically?
Upvotes: 0
Views: 263
Reputation: 8567
As said here, you can use split()
. Apparently, it doesn't work well when a group contains a single observation, so I added User1 bis
to show you. Also, you need to create a category for those whose group is NA
(I put "Without group" here so that it is alphabetically at the end of the list of inputs).
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)
Upvotes: 2