Selection problem of bucketlist in sortable package - r

There are 3 districts which are A, B, and C in my data. I would like to establish a new district from the subdistricts of the current districts. For example, I select 2 of 3 districts via selectInput. And then, I would like to use bucket_list for selecting the subdistricts. The bucket list should show the subdistricts of selected districts. I do not want to see subdistricts of 3rd districts on a bucket list. I want to see only what I selected via selectInput. I could not manage this. After that, I want to create some tables using the DT package based on what I selected in the bucket list. My codes are below. I would be happy if you could help.
Here’s code:
library(shiny)
library(semantic.dashboard)
library(ggplot2)
library(plotly)
library(DT)
library(sortable)
library(gsheet)
data <- gsheet2tbl('https://docs.google.com/spreadsheets/d/1TqFoIQzTYyWKP8N43jcAxAV71TTA7ldfeRcGtpqfarM/edit#gid=201611728')
ui <- dashboardPage(
dashboardHeader(color = "green",title = "NEW DISTRICT", inverted = TRUE, size = "very wide"),
dashboardSidebar(
size = "thin", color = "teal",
sidebarMenu(
menuItem(tabName = "dist", "NEW DISTRICT ESTABLISHMENT", icon = icon("tree")),
menuItem(tabName = "subdist", "NEW SUBDISTRICT ESTABLISHMENT", icon = icon("tree"))
)
),
dashboardBody(
tabItems(
selected = 1,
tabItem(
tabName = "dist",
fluidRow(
fluidPage( textInput("caption", "ENTER THE NAME OF THE NEW DISTRICT", "", width = 500, placeholder = "PLEASE ENTER NEW NAME HERE!"),
fluidRow(column(5, verbatimTextOutput("value1"))),
hr(),
fluidPage(
selectInput("select", label = h3("PLEASE SELECT THE DISTRICTS!"),
choices = (data$DISTRICT),
selected = 0,
multiple= TRUE),
hr(),
fluidRow(column(3, verbatimTextOutput("value")))
),
),
if(interactive()) {
bucket_list(
header = c("NEW DISTRICT ESTABLISHMENT"),
add_rank_list(
text = "PLEASE SELECT SUBDISTRICT HERE!",
labels = "x",
options = sortable_options(
multiDrag = TRUE),
),
add_rank_list(
text = "select the subdistricts of the new district"
),
add_rank_list(
text = "select the subdistrict of the current district"
),
add_rank_list(
text = "select the subdistrict of the current district 2"
)
)
}
),
)
)
),
theme = "cerulean"
)
server <- shinyServer(function(input, output, session) {
observe({ print(input$select)
#output$x <- data$SUBDISTRICT[data$DISTRICT == input$select]
#output$x <- data %>% filter(DISTRICT == input$select) %>% select(SUBDISTRICT)
#updateSelectInput(session,"SUBDISTRICT","Select a SUBDISTRICT Category",choices = unique(x))
})
output$value <- renderText({paste(input$select)
})
output$value1 <- renderText({ input$caption })
})
shinyApp(ui, server)
Also, when I remove # on these codes:
observe({ print(input$select)
#output$x <- data$SUBDISTRICT[data$DISTRICT == input$select]
#output$x <- data %>% filter(DISTRICT == input$select) %>% select(SUBDISTRICT)
#updateSelectInput(session,"SUBDISTRICT","Select a SUBDISTRICT Category",choices = unique(x))
The shiny close itself.

Perhaps this will meet your needs
library(shiny)
library(semantic.dashboard)
library(ggplot2)
library(plotly)
library(DT)
library(sortable)
library(gsheet)
data <- gsheet2tbl('https://docs.google.com/spreadsheets/d/1TqFoIQzTYyWKP8N43jcAxAV71TTA7ldfeRcGtpqfarM/edit#gid=201611728')
ui <- dashboardPage(
dashboardHeader(color = "green",title = "NEW DISTRICT", inverted = TRUE, size = "very wide"),
dashboardSidebar(
size = "thin", color = "teal",
sidebarMenu(
menuItem(tabName = "dist", "NEW DISTRICT ESTABLISHMENT", icon = icon("tree")),
menuItem(tabName = "subdist", "NEW SUBDISTRICT ESTABLISHMENT", icon = icon("tree"))
)
),
dashboardBody(
tabItems(
selected = 1,
tabItem(
tabName = "dist",
fluidRow(
fluidPage( textInput("caption", "ENTER THE NAME OF THE NEW DISTRICT", "", width = 500, placeholder = "PLEASE ENTER NEW NAME HERE!"),
fluidRow(column(5, verbatimTextOutput("value1"))),
hr(),
fluidPage(
selectInput("select", label = h3("PLEASE SELECT THE DISTRICTS!"),
choices = unique(data$DISTRICT),
selected = 0,
multiple= TRUE),
hr(),
fluidRow(column(3, verbatimTextOutput("value"))),
DTOutput("t1"),
selectInput("subdistrict", label = h3("PLEASE SELECT THE SUBDISTRICTS!"),
choices = unique(data$SUBDISTRICT),
selected = 0,
multiple= TRUE)
)
),
uiOutput("mybucket")
),
)
)
),
theme = "cerulean"
)
server <- shinyServer(function(input, output, session) {
dat <- reactive({
data[data$DISTRICT %in% req(input$select),]
})
output$mybucket <- renderUI({
req(dat())
bucket_list(
header = c("NEW DISTRICT ESTABLISHMENT"),
add_rank_list(
text = "PLEASE SELECT SUBDISTRICT HERE!",
labels = unique(dat()$SUBDISTRICT),
options = sortable_options(
multiDrag = TRUE),
),
add_rank_list(
text = "select the subdistricts of the new district"
),
add_rank_list(
text = "select the subdistrict of the current district"
),
add_rank_list(
text = "select the subdistrict of the current district 2"
)
)
})
output$t1 <- renderDT(dat())
observeEvent(input$select, {
updateSelectInput(session,"subdistrict","Select a SUBDISTRICT Category",choices = unique(dat()$SUBDISTRICT))
})
output$value <- renderText({paste(input$select)})
output$value1 <- renderText({ input$caption })
})
shinyApp(ui, server)

Related

need help fixing shiny dashboard?

I recently started using Shiny and I need help with shiny dashboard errors. I am trying to build an app using Shiny Dashboard, But I keep getting errors: "Error in tagAssert(sidebar, type = "aside", class = "main-sidebar") :
object 'sidebar' not found"
Can Someone help me fix the error??
Thanks in Advance
library(shiny)
library(shinydashboard)
library(DT)
library(tidyverse)
library(plotly)
covid <- read.csv("covid.csv")
covid_deaths <- read.csv("COVID_DEATHS_UK.csv")
noncovid_deaths <- read.csv("NON_COVID_DEATHS_UK.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
function(request){
sidebar <- dashboardSidebar(
hr(),
sidebarMenu(id="tabs",
menuItem("Global COVID data",
menuSubItem("COVID vaccinations: Deaths Vs All variable", tabName = "Dashboard"),
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
menuSubItem("Scatterplot", tabName = "Scatterplot", icon = icon("line-chart")),
menuSubItem("Regression", tabName = "Regression", icon = icon("cog")),
menuSubItem("Multicollinearity", tabName = "Multicollinearity", icon = icon("line-chart")),
menuSubItem("Summary", tabName = "Summary", icon = icon("file-o-text")),
menuSubItem("DataTable", tabName = "DataTable", icon = icon("table"), selected=TRUE)
),
menuItem("COVID_Deaths", tabName = "COVID Deaths", icon = icon("line-chart")),
menuItem("NonCOVID_Deaths", tabName = "Non COVID Deaths", icon = icon("line-chart"))
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "Scatterplot",
fluidRow(
column(width = 6,
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation")),
tabPanel(helpText("Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths"),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
))))),
tabItems(
tabItem(tabName = "Regression",
fluidRow(
column(width = 6,
tabPanel(verbatimTextOutput(outputId = "regsum"),
verbatimTextOutput(outputId = "indprint"),
verbatimTextOutput(outputId = "depprint")),
tabPanel(helpText("Select input for Independent variables"),
selectInput(inputId = "indvar", label = "Independent Variable", multiple = TRUE,
choices = list("total_cases", "total_vaccinations", "people_fully_vaccinated", "total_boosters","stringency_index",
"population_density", "aged_65_older","gdp_per_capita","extreme_poverty", "cardiovasc_death_rate", "diabetes_prevalence", "handwashing_facilities", "life_expectancy","human_development_index")),
helpText("Select input for dependent variables"),
selectInput(inputId = "depvar", label = "Dependent variable", multiple = FALSE,
choices = list("total_deaths","new_deaths","new_cases")))
)))),
tabItems(
tabItem(tabName = "Multicollinearity",
fluidRow(
tabPanel(img(src="Multicollinearity.png"))))),
tabItems(
tabItem(tabName = "Summary",
fluidRow(tabPanel(
verbatimTextOutput("summary")
)))),
tabItems(
tabItem(tabName = "DataTable",
fluidRow(tabPanel(DTOutput("dataset")),
tabPanel(helpText("Select the Download Format"),
radioButtons("type", "4. Format type:",
choices = c("Excel (csv)", "Text(tsv)", "Doc")),
br(),
helpText("Click on the download button to download dataset"),
downloadButton("downloadData", "Download"))))),
tabItems(tabItem(tabName = "COVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist1")),
tabPanel(helpText("Select Variables for a COVID deaths"),
selectInput(inputId = "Yaxis", label = "yaxis:",
choices = names(subset(covid_deaths, select = -c(Week_number,Week_ending)))))))),
tabItems(tabItem(tabName = "NonCOVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist2")),
tabPanel(helpText("Select Variables for a NOn- COVID deaths"),
selectInput(inputId = "ya", label = "Yaxis:",
choices = names(subset(noncovid_deaths, select = -c(Week_number,Week_ending))))))))
)
}
ui <- dashboardPage(skin = "black",
dashboardHeader(title = title),
sidebar,body)
server <- function(input, output, session) {
output$location <- renderPrint({
locationfilter <- subset(covid, covid$location == input$location)
})
output$summary <- renderPrint({
summary(covid)
})
datasetinput <- reactive({covid})
fileExt <- reactive({
switch(input$type,
"Excel (csv)" = "csv", "Text (tsv)" = "tsv", "Doc" = "doc")
})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$downloadData <- downloadHandler(
filename = function(){
paste("covid", fileExt(),sep = ".")
},
content = function(file){
sep <- switch(input$type,
"Excel (csv)" = ",", "Text (tsv)" = "\t", "Doc" = " ")
write.table(datasetinput(), file, sep = sep, row.names = FALSE)
}
)
output$scatterplot <- renderPlotly({
#ggplot(subset(covid, covid$location == input$location),aes(y= input$y,x=input$x))+geom_point()
ggplotly(ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index"))
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
output$hist1 <- renderPlotly({
ggplotly(ggplot(covid_deaths, aes(x=Week_number, y= .data[[input$Yaxis]]))+
geom_point()
)
})
output$hist2 <- renderPlotly({
ggplotly(ggplot(noncovid_deaths, aes(x=Week_number, y= .data[[input$ya]]))+
geom_point()
)
})
lm1 <- reactive({lm(reformulate(input$indvar, input$depvar), data = subset(covid, covid$location == input$location))})
output$depPrint <- renderPrint({input$depvar})
output$indPrint <- renderPrint({input$indvar})
output$regsum <- renderPrint({summary(lm1())})
}
# Shiny dashboard
shiny::shinyApp(ui, server)

Shiny/R - Make a single button send multiple responses

I need the "send" button to send all app info to a spreadsheet saved in Google Drive (not just the first info); each for a column (Name, Age, Birth...). Thanks!
This is my code:
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(googlesheets4)
library(googledrive)
library(readr)
library(DT)
# Dashboard
ui <- dashboardPage(skin = "red",
dashboardHeader(
title = "Controller"
),
dashboardSidebar(
sidebarMenu(
menuItem(
"Home",
tabName = "home",
icon = icon("home"))
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "home", h2("Hello"),
br(),
box(
h2(icon("id-card"), "Client"),
width = 2000,
br(),
# Insery name
textInputIcon(
inputId = "name",
label = "Name"),
# Birth
dateInput(
inputId = "dob",
label ="Birth",
min = "1960-01-01",
max = Sys.Date(), format = "yyyy/mm/dd",
language = "en"),
textInputIcon(
inputId = "age",
label = "Age"),
# Phone
textInputIcon(
inputId = "phone",
label = "Phone"),
# E-mail
textInputIcon(
inputId = "email",
label = "E-mail"),
# Send
actionButton("send", "Send"),
)
)
)
)
)
# Server
server <- function(input, output, session) {
textname <- reactive({
as.data.frame(input$name)
})
observeEvent(input$sendname, {
Selfie <- gs4_get('link')
sheet_append(Selfie, data = textname())
})
observe({ dob <- input$dob
if(!is.null(dob)) {
days <- as.integer((Sys.Date() - as.Date(dob)))
years <- as.integer(days / 365)
months <- as.integer((days %% 365 ) / 30)
age <- paste(years, 'year(s)', months, 'month(s)')
#print(age)
updateTextInput(session, "age", value = age)
}
})
}
# App
shinyApp(ui = ui, server = server)
We can loop through input and gather everything in a df.
observeEvent(input$send, {
require(tidyverse)
#gather info of all the relevant inputs
client_df <- c('name', 'dob', 'age', 'phone', 'email') %>%
map_dfc(~ tibble("{.x}" := input[[.x]]))
print(client_df) #this will print a df with one row in the console
#Selfie <- gs4_get('link')
#sheet_append(Selfie, data = client_df)
})

Reactively updating sidebar in modular Shiny app

I have a modularized Golem app using bs4Dash. I want to update the active sidebar tab from an actionBttn that is dynamically generated from renderUI. While updatebs4ControlbarMenu works as expected as shown here, it does not work in the modularized version of the application. What am I doing wrong? I suspect it is related to input[[btnID]] management across modules but I struggle to find the solution.
Working example without modules as shown here:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
shinyApp(
ui = bs4DashPage(
sidebar_collapsed = FALSE,
controlbar_collapsed = TRUE,
enable_preloader = FALSE,
navbar = bs4DashNavbar(skin = "dark"),
sidebar = bs4DashSidebar(
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
fluidRow(
pickerInput(
inputId = "car",
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = "gear",
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput("uiboxes")
)
)
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
),
server = function(input, output, session) {
submtcars <- reactive({
req(input$car, input$gear)
mtcars %>%
mutate(
carnames = rownames(mtcars)) %>%
filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
str_c("Number of gears:", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = btnID,
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "tab2"
)
})
})
})
}
)
Modularized attempt not working:
library(shiny)
library(shinyWidgets)
library(bs4Dash)
library(tidyverse)
mod_exlib_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
pickerInput(
inputId = ns("car"),
label = "Car",
choices = row.names(mtcars),
selected = head(row.names(mtcars), 3),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
),
pickerInput(
inputId = ns("gear"),
label = "Gear",
choices = unique(mtcars$gear),
selected = unique(mtcars$gear),
multiple = TRUE,
options = list(
`actions-box` = TRUE)
)
),
fluidRow(
column(6,
uiOutput(ns("uiboxes"))
)
)
)
}
mod_exlib_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
submtcars <- reactive({
# req(input$car, input$gear)
mtcars %>%
dplyr::mutate(
carnames = rownames(mtcars)) %>%
dplyr::filter(
carnames %in% input$car &
gear %in% input$gear
)
})
observeEvent( submtcars(), {
n_ex <- nrow(submtcars())
output$uiboxes <- renderUI({
lapply(1:n_ex, FUN = function(j) {
print(paste("j is ", j))
bs4Box(
title = submtcars()$carnames[j],
width = 12,
paste("Number of gears: ", submtcars()$gear[j]),
btnID <- paste0("btnID", j),
print(btnID),
fluidRow(
column(
2,
actionBttn(
inputId = ns(btnID),
icon("search-plus")
)
)
)
)
})
})
lapply(1:n_ex, function(j) {
btnID <- paste0("btnID", j)
observeEvent(input[[btnID]] , {
print(btnID)
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "exdet2"
)
})
})
})
})
}
app_ui <- tagList(
bs4DashPage(
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(
expand_on_hover = TRUE,
inputId = "sidebarState",
bs4SidebarMenu(
id = "sidebr",
bs4SidebarMenuItem(
"Tab 1",
tabName = "tab1"
),
bs4SidebarMenuItem(
"Tab 2",
tabName = "tab2"
)
)
),
bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab1",
h1("Welcome!"),
mod_exlib_ui("exlib_ui_1")
),
bs4TabItem(
tabName = "tab2",
h4("Yuhuuu! You've been directed automatically in Tab 2!")
)
)
)
)
)
app_server <- function( input, output, session ) {
# Your application server logic
mod_exlib_server("exlib_ui_1")
}
shinyApp(
ui = app_ui,
server = app_server)
After exploring the example of function updatebs4TabSetPanel() that is in the same family, it seems that the selected value needs to be a number.
Hence, you can use this code with CRAN version 0.5.0:
updatebs4ControlbarMenu(
session,
inputId = "sidebr",
selected = "2" #"exdet2"
)

shiny: pickerIntput choices based on search bar

hi i im trying to have the 'choices' in my pickerInput be dependent on what the user types in the search bar above. im using a spotify r package and if you search a certain artist the api returns a table of artists of the similar name and you need to choose which artist you want. anyways i want that table to go into the pickerInput and i can't seem to get it work.
ui <- dashboardPage(skin = "green",
dashboardHeader(title = "Lyric Prediction"),
dashboardSidebar(
sidebarMenu(
menuItem("Overview", tabName = "Overview", icon = icon("search")),
menuItem("Analysis", tabName = "Analysis", icon = icon("bar-chart-o"))
)
),
dashboardBody(
tags$head(
tags$style(HTML(".fa { font-size: 18px; }"))
),
tabItems(
# First tab content
tabItem(tabName = "Overview",
fluidRow(
column(12,
searchInput(
inputId = "search", label = "Search Artist on Spotify",
placeholder = "Search",
btnSearch = icon("search"),
btnReset = icon("remove"),
width = "500px"
)
), align = "center"
),
#HERE - how can i have pickerInput take in the output
#of "res" from the server?
fluidRow(pickerInput(choices = "res")
)),
)
)
server <- function(input, output) {
#function to take search input
#output list of possible artists
output$res <- renderTable({
#Rspotify
possibleArtists <- searchArtist(input$search,token=my_oauth)
possibleArtists <- as_tibble(possibleArtists)
myCols <- c("display_name","id")
colNums <- match(myCols,names(possibleArtists))
possibleArtists <- possibleArtists %>%
select(colNums)
possibleArtists
})
}
shinyApp(ui, server)
Use update method in an observeEvent like this:
observeEvent(input$search, {
#Rspotify
possibleArtists <- searchArtist(input$search,token=my_oauth)
possibleArtists <- as_tibble(possibleArtists)
myCols <- c("display_name","id")
colNums <- match(myCols,names(possibleArtists))
possibleArtists <- possibleArtists %>%
select(colNums)
updatePickerInput(
session = session,
inputId = "picker",
choices = possibleArtists
)
}, ignoreInit = TRUE)
Full example:
library(shiny)
library(shinydashboard)
library(shinyWidgets)
ui <- dashboardPage(
skin = "green",
dashboardHeader(title = "Lyric Prediction"),
dashboardSidebar(
sidebarMenu(
menuItem("Overview", tabName = "Overview", icon = icon("search")),
menuItem("Analysis", tabName = "Analysis", icon = icon("bar-chart-o"))
)
),
dashboardBody(
tags$head(
tags$style(HTML(".fa { font-size: 18px; }"))
),
tabItems(
# First tab content
tabItem(
tabName = "Overview",
fluidRow(
column(12,
searchInput(
inputId = "search", label = "Search Artist on Spotify",
placeholder = "Search",
btnSearch = icon("search"),
btnReset = icon("remove"),
width = "500px"
)
), align = "center"
),
pickerInput(inputId = "picker", label = "Choose an artist:", choices = NULL)
)
)
)
)
server <- function(input, output, session) {
observeEvent(input$search, {
updatePickerInput(
session = session,
inputId = "picker",
choices = c("The Beatles",
"The Beatles Recovered Band",
"Yesterday - A Tribute To The Beatles",
"The Beatles Revival Band & Orchestra")
)
}, ignoreInit = TRUE)
}
shinyApp(ui, server)

ConditionalPanel with more than one condition are true

I am having a conditionalPanel problem when more than one option is valid.
A part of my code that the user makes two choices in sequence, so that filters are made in the database.
In the first choice, a State will be selected from a list of possibilities. It is important to know that the user can select more than one State.
In the second choice, the City will be selected from a list of possibilities. In this second choice, the user can also select more than one City.
As I said, important information is that the user can select more than one state, so from that multiple choice of states, it should be shown the cities of all selected states.
Everything works fine when the user selects only one state. The problem with my code starts when it selects more than one state, the ConditionalPanel simply disappears (nothing is shown, not even the first option that was already shown). It only appears again when the user removes the selections, keeping only one.
If anyone has a few minutes to help me to sort out this problem I'm facing, I'll be very grateful.
library(shiny)
library(shinydashboard)
library(readr)
state_options <- c("1. Texas", "2. Massachusetts", "3. Colorado")
options_state_texas <- c("Alamo", "Alton", "Angus", "Atlanta", "Aurora",
"Brownsboro", "Premont", "Princeton", "Red Oak",
"Staples", "Texas City")
options_state_massachusetts <- c("Boston", "Cambridge", "Chelsea", "Springfield")
options_state_colorado <- c("Aspen", "Aurora", "Avon", "Cortez", "Denver",
"Vail")
createMainPanel <- function(index_id) {
mainPanel(
width = 12,
tabsetPanel(
tabPanel(
strong("Split"),
br(),
box(
title = strong("State:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_state"),
label = NULL,
choices = state_options
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '1. Texas'",
box(
title = strong("Cities state 1:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_1"),
label = NULL,
choices = options_state_texas
)
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '2. Massachusetts'",
box(
title = strong("Cities state 2:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_2"),
label = NULL,
choices = options_state_massachusetts
)
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state == '3. Colorado'",
box(
title = strong("Cities state 3:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_checkbox_city_3"),
label = NULL,
choices = options_state_colorado
)
)
)
)
)
)
}
createTabItem <- function(title, index_id) {
tabItem(
tabName <- paste0(index_id, "_tab"),
h2(title),
createMainPanel(index_id))
}
createBox <- function(session, index_id, opcoes){
updateCheckboxGroupInput(
session,
index_id,
choices = c(opcoes))
}
ui <- dashboardPage(
dashboardHeader(disable = TRUE),
dashboardSidebar(
title = img(src='logo.png', height = 60, width = 180, style = "display: block;
margin-left: auto; margin-right: auto;"),
HTML("<br><br>"),
width = 230,
sidebarMenu(
menuItem(strong("Sales"), tabName = "distribution_of_sales_sub_tab")
)
),
dashboardBody(
tabItems(
createTabItem(strong("Distribution of sales"),
"distribution_of_sales_sub")
)
)
)
server <- function(input, output, session) {
observe({
createBox(session,"distribution_of_sales_sub_state", state_options)
createBox(session,"distribution_of_sales_sub_checkbox_city_1",
options_state_texas)
createBox(session,"distribution_of_sales_sub_checkbox_city_2",
options_state_massachusetts)
createBox(session,"distribution_of_sales_sub_checkbox_city_3",
options_state_colorado)
})
}
shinyApp(ui, server)
You need to change your conditions to
condition = "input.distribution_of_sales_sub_state.includes('1. Texas')",
condition = "input.distribution_of_sales_sub_state.includes('2. Massachusetts')",
condition = "input.distribution_of_sales_sub_state.includes('3. Colorado')",
EDIT: SOLUTION FOR QUESTION IN COMMENTS
This definitely is not the best solution but this should give you what you want and a good start to make it better.
library(shiny)
library(shinydashboard)
library(readr)
state_options <- c("1. Texas", "2. Massachusetts", "3. Colorado")
options_state_texas <- c("Alamo", "Alton", "Angus", "Atlanta", "Aurora",
"Brownsboro", "Premont", "Princeton", "Red Oak",
"Staples", "Texas City")
options_state_massachusetts <- c("Boston", "Cambridge", "Chelsea", "Springfield")
options_state_colorado <- c("Aspen", "Aurora", "Avon", "Cortez", "Denver",
"Vail")
city_options <- c()
createMainPanel <- function(index_id) {
mainPanel(
width = 12,
tabsetPanel(
tabPanel(
strong("Split"),
br(),
box(
title = strong("State:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0(index_id, "_state"),
label = NULL,
choices = state_options
)
),
conditionalPanel(
condition = "input.distribution_of_sales_sub_state != ''",
uiOutput("city")
)
)
)
)
}
createTabItem <- function(title, index_id) {
tabItem(
tabName <- paste0(index_id, "_tab"),
h2(title),
createMainPanel(index_id))
}
createBox <- function(session, index_id, opcoes){
updateCheckboxGroupInput(
session,
index_id,
choices = c(opcoes))
}
ui <- dashboardPage(
dashboardHeader(disable = TRUE),
dashboardSidebar(
title = img(src='logo.png', height = 60, width = 180, style = "display: block;
margin-left: auto; margin-right: auto;"),
HTML("<br><br>"),
width = 230,
sidebarMenu(
menuItem(strong("Sales"), tabName = "distribution_of_sales_sub_tab")
)
),
dashboardBody(
tabItems(
createTabItem(strong("Distribution of sales"),
"distribution_of_sales_sub")
)
)
)
server <- function(input, output, session) {
output$city <- renderUI({
box(
title = strong("Cities state:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = paste0("distribution_of_sales_sub", "_checkbox_city_1"),
label = NULL,
choices = cities()
)
)
})
city_options1 <- c()
city_options2 <- c()
city_options3 <- c()
cities <- reactive({
if(c("1. Texas") %in% input$distribution_of_sales_sub_state ){
city_options1<- c(options_state_texas)
}
if (c("2. Massachusetts") %in% input$distribution_of_sales_sub_state) {
city_options2 <- c(options_state_massachusetts)
}
if (c("3. Colorado") %in% input$distribution_of_sales_sub_state ) {
city_options3 <- c(options_state_colorado)
}
city_options <- c(city_options1,city_options2, city_options3)
city_options <- sort(city_options)
})
observe({
createBox(session,"distribution_of_sales_sub_state", state_options)
createBox(session,"distribution_of_sales_sub_checkbox_city_1",
options_state_texas)
createBox(session,"distribution_of_sales_sub_checkbox_city_2",
options_state_massachusetts)
createBox(session,"distribution_of_sales_sub_checkbox_city_3",
options_state_colorado)
})
}
shinyApp(ui, server)
Your code is not reproducible at all, You should take care of that before posting the question.
Well my guess without proper code and data would be to move all your conditions to server.R. So in ui.R you should create for each state: uiOutput("state1") (its for the first conditional state: Texas), then in server.R:
output$state1 <- renderUI({
if(any(input$state == '1. Texas')){
box(
title = strong("Cities state 1:"),
status = "primary",
width = 3,
collapsible = TRUE,
checkboxGroupInput(
inputId = "checkbox_city_1"),
label = NULL,
choices = options_state_texas
)}
else{NULL})

Resources