Can I create Submit button with observeEvent in R? - r

i just stuck in observeEvent when i want to create submit button , the event doesn't make any action when i got to clicked, for the example here my code for the modal:
column(width = 6,
bs4Card(width = 12, collapsible = FALSE, title = "Follow Up",
selectInput("cara_fu", "Cara Follow up",
choices = c('Call','Whatsapp', 'Visit')),
selectInput("hasil_fu", "Hasil Follow up",
choices = c('Survey', 'Batal', 'Unreachable')),
textAreaInput("ket_fu", "Keterangan",height = '100px'),
footer = actionButton("submit_fu", "Submit", status = "success")
)
)
then when the form has been input by the value, the observeEvent will be generate by this code :
# IF USER CLICKS SUBMIT FOLLOWUP, SAVE THE DATA IN DATABASE
observeEvent(input$submit_fu, {
text = tagList(
selectInput("cara_fu", "Cara Follow up",
choices = c('Call','Whatsapp', 'Visit'), selected = df$cara_fu),
selectInput("hasil_fu", "Hasil Follow up",
choices = c('Survey','Batal', 'Unreachable'), selected = df$hasil_fu),
textInput("ket_fu", "Keterangan")
)
}) # End observe submit button
and when this button cliked nothing happen , im glad when all of u can find whats wrong here thanks
and here for the full code :
shiny::observeEvent(input$current_id, {
shiny::req(!is.null(input$current_id) &
stringr::str_detect(input$current_id,
pattern = "followup"
))
rv$dt_row <- which(stringr::str_detect(rv$df$Buttons,
pattern = paste0("\\b", input$current_id, "\\b")
))
showModal(
modalDialog(title = "Followup", easyClose = TRUE, size = "l",
fluidPage(
fluidRow(
column(width = 6,
bs4Card(width = 12, collapsible = FALSE, title = "Profile Summary",
boxProfile(
image = "https://adminlte.io/themes/AdminLTE/dist/img/user4-128x128.jpg",
title = (rv$df$nama_customer[rv$dt_row]),
subtitle =(rv$df$no_hp_customer[rv$dt_row]),
bordered = TRUE,
boxProfileItem(
title = "Jadwal Followup",
description =rv$df$scheduled_followup[rv$dt_row]),
boxProfileItem(
title = "Produk",
description = rv$df$produk[rv$dt_row]),
boxProfileItem(
title = "Status",
description = rv$df$status[rv$dt_row])
)
),
bs4Card(width = 12, collapsible = FALSE, title = "History Followup",
timelineBlock(
width = 12,
timelineLabel(as.Date(Sys.Date()), color = "primary"),
timelineItem(
title = "Followup 1",
icon = icon("book"),
color = "secondary",
time = "now",
"This is the body"
),
timelineLabel(as.Date(Sys.Date()), color = "primary"),
timelineItem(
title = "Followup 3",
icon = icon("book"),
color = "secondary"
)
)
)
),
column(width = 6,
bs4Card(width = 12, collapsible = FALSE, title = "Follow Up",
selectInput("cara_fu", "Cara Follow up",
choices = c('Call','Whatsapp', 'Visit')),
selectInput("hasil_fu", "Hasil Follow up",
choices = c('Survey', 'Batal', 'Unreachable')),
textAreaInput("ket_fu", "Keterangan",height = '100px'),
footer = actionButton("submit_fu", "Submit", status = "success")
)
)
)
),
footer = tagList(
modalButton("Cancel"),
actionButton("ok", "OK")
)
)
)
observeEvent(input$submit_fu, {
text = tagList(
selectInput("cara_fu", "Cara Follow up",
choices = c('Call','Whatsapp', 'Visit'), selected = df$cara_fu),
selectInput("hasil_fu", "Hasil Follow up",
choices = c('Survey','Batal', 'Unreachable'), selected = df$hasil_fu),
textInput("ket_fu", "Keterangan")
)
}) # End observe submit button
}) # End observe followup button
}
# Run the application
shinyApp(ui = ui, server = server)

Related

modualized shiny app ui renders all plots on top of one another

I have a shiny app, fully built, that I had built all in one script. Everything was working, the ui, etc. and I wanted to modularize the app to make the code a bit more readable. Now all the plots render on top of each other and I can't figure out why. I've tried using pageContainer, sidbarLayout, sidePanel and mainPanel, fluidPage, fixedPage, etc. and none have worked. I'm also using pagePiling with my main ui, so not sure if that has sometimes to do with it? Any help would be much appreciated!
Please find the full code here: https://github.com/eoefelein/COVID_Business_Recovery_and_Social_Capital/tree/master/socialCapitalEmployment
Here is what my ui code looks like:
ui <- tagList(
pagePiling(
center = TRUE,
sections.color = c("#3333FF", "#E6E6E6"),
menu = c(
"Home" = "home",
"Map" = "map",
"Series" = "ts",
"PCA" = "pca",
"Predict" = "predict",
"About" = "about"
),
pageSectionImage(
center = TRUE,
img = "",
menu = "home",
h1(("title"), class = "header shadow-dark"),
h3(
class = "light footer",
"by",
tags$a("news-r", href = "https://news-r.org", class = "link")
)
),
pageSection(center = TRUE,
menu = "map",
mod_map_ui("map"),
br()),
pageSection(center = TRUE,
menu = "ts",
mod_ts_ui("ts"),
br()),
pageSection(center = TRUE,
menu = "pca",
mod_pca_ui("pca"),
br()),
pageSection(
center = TRUE,
menu = "predict",
mod_predict_ui("predict"),
),
pageSection(
center = TRUE,
menu = "about",
h1("About", class = "header shadow-dark"),
h2(
class = "shadow-light",
tags$a(
"The code",
href = "https://github.com/news-r/fopi.app",
target = "_blank",
class = "link"
),
"|",
tags$a(
"The API",
href = "https://github.com/news-r/fopi",
target = "_blank",
class = "link"
)
),
h3(
class = "light footer",
"by",
tags$a("news-r", href = "https://news-r.org", class = "link")
)
)
)
)
Here is my first module's ui:
mod_map_ui <- function(id) {
ns <- NS(id)
tagList(
fluidPage(
h1("Employment & Social Capital across the U.S by County"),
center = TRUE,
column(9, leafletOutput(ns("map"), height = "100vh")),
column(
3,
shinyWidgets::radioGroupButtons(
inputId = ns("idx"),
label = "Metric",
choices = c(unique(social_indices$name)),
checkIcon = list(yes = icon("ok",
lib = "glyphicon"))
)
)
))
}
And here is my second module's ui:
mod_ts_ui <- function(id) {
ns <- NS(id)
tagList(
fixedPage(
h2("Employment by County", align = "center"),
fixedRow(
column(
4,
selectizeInput(
inputId = ns("dataset"),
label = "Choose a county:",
choices = c(unique(employment["countyfips"])),
multiple = TRUE,
selected = "Travis County, Texas",
options = list(create = TRUE)
)
),
column(
8, (echarts4r::echarts4rOutput(ns("ts_plot")))
)
)
)
)
}
okay, so I fixed it and what I think fixed it was specifying a color for each section:
pagePiling(
center = TRUE,
sections.color = c("#7b959c", "#445768","#b9bdc9","#f6e7ea","#e2e2e2","#1e4356"),
menu = c(
"Home" = "home",
"Map" = "map",
"Series" = "ts",
"PCA" = "pca",
"Predict" = "predict",
"About" = "about"
),
Very strange, but after I did that, each plot presented as it should, in it's own section. Hope this helps someone in the future!

Use string from server.R as argument in a function within ui.r

I'm using shinydashboardPlus() to include a timeline in an app I'm developing. I want each timelineItem() icon to change colour depending on whether a stage is marked as complete. When a stage is incomplete, I would like the icon to be grey. When a checkboxInput() is selected, I would like the colour to change to olive.
I have written the server-side logic such that when checkboxInput is FALSE the string 'grey' is returned but when TRUE the string 'olive' is returned. I need to pass this string to the argument color in timelineItem(). I have tried passing the string to the argument using textOutput() but this doesn't work. Any ideas how I can pass the correct colour string to color?
Here's an MRE:
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(shinydashboardPlus)
ui <- dashboardPagePlus(
header = dashboardHeaderPlus(title = "Quality & Assurance Dashboard"),
sidebar = dashboardSidebar(
),
body = dashboardBody(
fluidRow(
box(width = 9,
title = "Assurance Timeline",
status = "info",
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
time = "now",
footer = "",
textOutput("survey_released_colour")
)
)
),
box(width = 3,
title = "Stage Sign-Off",
status = "info",
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
color = "olive",
time = "",
footer = "",
"Check here when Stage 1 complete.",
checkboxInput(inputId = "survey_release", "Surveys Released", value = FALSE, width = NULL)
)
)
)
)
),
)
server <- function(input, output) {
output$survey_released_colour<-renderText({
if (input$survey_release == TRUE){
paste0("olive")
}
else
paste0("grey")
})
}
app<-shinyApp(ui = ui, server = server)
runApp(app, host="0.0.0.0",port=5050, launch.browser = TRUE)
from the basic rules of Shiny you can't use any server component inside ui.R. You can use an condition for changing the color in server side.
My try:
library(shinydashboardPlus)
ui <- dashboardPagePlus(
header = dashboardHeaderPlus(title = "Quality & Assurance Dashboard"),
sidebar = dashboardSidebar(
),
body = dashboardBody(
fluidRow(
box(width = 9,
title = "Assurance Timeline",
status = "info",
uiOutput("timeline")
),
box(width = 3,
title = "Stage Sign-Off",
status = "info",
checkboxInput(inputId = "survey_release", "Surveys Released", value = FALSE, width = NULL)
)
)
)
)
server <- function(input, output) {
output$timeline<-renderUI({
if (input$survey_release == TRUE)
{
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
#color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
color ='red',
time = "now",
footer = ""
)
)
}
else
{
timelineBlock(
timelineEnd(color = "danger"),
timelineLabel("Start", color = "teal"),
timelineItem(
title = "Stage 1",
icon = "gears",
#color = textOutput("survey_released_colour"), # Need to paste the correct colour string here
color ="green",
time = "now",
footer = ""
)
)
}
})
}
shinyApp(ui, server)
let me know if this helps.

Trying to create a reactive graph that will take in multiple different inputs in shiny

I have added multiple select inputs to my shiny app in the sidebar and in the main body and want to create a graph that will change when any of those inputs have been selected or changed but I keep getting the error Warning: Error in : Result must have length 56127, not 0.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Human Trafficking"),
dashboardSidebar(
sidebarMenu(
selectInput("Source", "Choose a Data Source: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL),
dateInput("startdate", "Start Date:", value = "2009-01-01", format = "dd-mm-yyyy",
min = "2009-01-01", max = "2019-08-26"),
dateInput("enddate", "End Date:", value = "2019-08-27", format = "dd-mm-yyyy",
min = "2009-01-02", max = "2019-08-27"),
selectInput("Nationality", "Select a nation: ", choices = " "),
actionButton("button", "Apply")
)
),
dashboardBody(
fluidRow(
box(width = 4, solidHeader = TRUE,
selectInput("traffickingType", "Choose a trafficking type: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("traffickingSubType", "Choose a trafficking sub type: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
),
box(width = 4, solidHeader = TRUE,
selectInput("gender", "Choose a gender: ", choices = " ", selected = NULL,
multiple = TRUE, selectize = TRUE, width = NULL, size = NULL)
)
),
fluidRow(
box(width = 12,
plotlyOutput('coolplot')
)
)
)
)
Server:
server <- function(input, output, session) {
genderVic = sort(unique(ngo$Victim.Gender))
updateSelectInput(session, "gender", choices = genderVic)
traffickingSub = sort(unique(ngo$Trafficking.Sub.Type))
updateSelectInput(session, "traffickingSubType", choices = traffickingSub)
trafficking = sort(unique(ngo$Trafficking.Type))
updateSelectInput(session, "traffickingType", choices = trafficking)
traffickerNationalities = sort(unique(ngo$Trafficker.Nationality))
updateSelectInput(session, "TraffickerNation", choices = traffickerNationalities)
dataSource = sort(unique(ngo$Data.Provided.By))
updateSelectInput(session, "Source", choices = dataSource)
nationalities = sort(unique(ngo$Victim.Nationality))
updateSelectInput(session, "Nationality", choices = nationalities)
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality == input$Nationality,
Victim.Gender == input$gender,
Trafficking.Type == input$traffickingType
)
p = ggplot(ngo, aes(x = Victim.Age, fill = Trafficking.Type)) +
geom_bar(position = "stack")
ggplotly(p) %>%
layout(showlegend = FALSE)
})
}
So currently only have it calling three of the inputs to test it but still getting an error.
It should work after the error is displayed once you select a gender and trafficking type in your example. The reason for the error is that renderPlotly is expecting values for input$traffickingType and input$gender but these start out as NULL.
Add a req for each of those selectInputs:
output$coolplot <- renderPlotly({
ngo <-
ngo %>%
filter(Victim.Nationality == input$Nationality,
Victim.Gender == req(input$gender),
Trafficking.Type == req(input$traffickingType)
)
p = ggplot(ngo, aes(x = Victim.Age, fill = Trafficking.Type)) +
geom_bar(position = "stack")
ggplotly(p) %>%
layout(showlegend = FALSE)
})

Shiny radio button not getting rendered initially when the app starts

I am doing some timeseries analysis and have created a shiny app where when the app starts sample timeseries data is uploaded or the user can upload csv dataset from his local directory....
Sample Dataset:
df
month passengers
1 01-01-2000 2072798
2 01-02-2000 2118150
3 01-03-2000 2384907
4 01-04-2000 2260620
5 01-05-2000 2386165
6 01-06-2000 2635018
7 01-07-2000 2788843
8 01-08-2000 2942082
9 01-09-2000 2477000
10 01-10-2000 2527969
11 01-11-2000 2161170
12 01-12-2000 2175314
13 01-01-2001 2307525
14 01-02-2001 2196415
15 01-03-2001 2545863
library(signal)
library(shiny)
library(AnomalyDetection) #devtools::install_github("twitter/AnomalyDetection")
library(ggplot2)
# Define UI for application that draws a histogram
library(shinydashboard)
library(shinycssloaders)
library(googleVis)
shinyUI(dashboardPage(skin = "green",
dashboardHeader(title = "Anomaly Detection in Time series",
titleWidth = 350),
dashboardSidebar(
sidebarUserPanel("Nishant Upadhyay",
image = "nishantcofyshop.jpg"
),
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("database")),
menuItem("Filters", tabName = "filter", icon = icon("filter")),
menuItem("Anomalies", tabName = "anomaly", icon = icon("check")),
#menuItem("Save Data", tabName = "save", icon = icon("save"))
menuItem("About The App", tabName = "Help", icon = icon("info-circle"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data",
fluidRow(
box(
title = "Data scatter Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput("dataChart"),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
radioButtons(
"data_input","",
choices = list("Load sample data" = 1,
"Upload csv file" = 2
)
),
conditionalPanel(
condition = "input.data_input=='1'",
h5("Sample dataset of Lebron James basketball shots over the years")
),
conditionalPanel(
condition = "input.data_input=='2'",
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),','),
radioButtons('quote', 'Quote',
c('None'='',
'Double Quote'='"',
'Single Quote'="'"),
'')
),
title = "Select Dataset",
status = "info",
solidHeader = T,
collapsible = T
),
box(
title = "Data",
status = "info",
solidHeader = T,
collapsible = T,
shinycssloaders::withSpinner(htmlOutput('contents'),type = getOption("spinner.type", default = 8),color = "red")
)# end of box
)## end of Fluid row
), ## end of tab item
tabItem(
tabName = "filter",
fluidRow(
box(
title = "Data Chart",
status = "primary",
solidHeader = T,
collapsible = T,
width = 12,
shinycssloaders::withSpinner(htmlOutput('dataChartFiltered'),type = getOption("spinner.type", default = 8),color = "red")
)
),
fluidRow(
box(
title = "Filters",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
radioButtons("filt", NULL,
c("None" = "none",
"Butterworth" = "butt",
"Type-II Chebyshev" = "cheby2")),
submitButton("Filter")
),
box(
title = "Butterworth",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("buttern", label = "Filter Order", value = "3"),
textInput("butterf", label = "Critical Frequencies", value = "0.1"),
radioButtons("buttert", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
),
box(
title = "Chebyshev",
status = "info",
solidHeader = T,
collapsible = T,
width = 4,
textInput("chebyn", label = "Filter Order", value = "5"),
textInput("chebyd", label = "dB of Pass Band", value = "20"),
textInput("chebyf", label = "Critical Frequencies", value = "0.2"),
radioButtons("chebyt", "Type",
c("Low-Pass" = "low",
"High-Pass" = "high"))
)
)
)
) ## end of tab items
) ## end of Dashboard
)
)
shinyServer(function(input, output){
dataframe<-reactive({
if (input$data_input == 1) {
tab <- read.csv("df.csv",header = T,stringsAsFactors = F)
} else if (input$data_input == 2) {
inFile <- input$file1
if (is.null(inFile))
return(data.frame(x = "Select your datafile"))
tab = read.csv(inFile$datapath, header = input$header,
sep = input$sep, quote = input$quote)
}
tt <- tryCatch(as.POSIXct(tab[,1]),error=function(e) e, warning=function(w) w)
if (is(tt,"warning") | is(tt,"error")) {
tab$Old = tab[,1]
tab[,1] = as.POSIXct(1:nrow(tab), origin = Sys.time())
} else {
tab[,1] = as.POSIXct(tab[,1])
}
tab
})
output$dataChart <- renderGvis({
if (!is.null(dataframe()))
gvisLineChart(dataframe()[,c(1,2)], xvar = colnames(dataframe())[1], yvar = colnames(dataframe())[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
})
output$contents <- renderGvis({
if (!is.null(dataframe()))
gvisTable(dataframe(),
options = list(page='enable'))
})
output$dataChartFiltered <- renderGvis({
if (input$filt == "none") {
return(NULL)
} else if (input$filt == "butt") {
bf <- butter(as.numeric(input$buttern), as.numeric(input$butterf), type = input$buttert)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (input$filt == "cheby2") {
ch <- cheby2(as.numeric(input$chebyn), as.numeric(input$chebyd),
as.numeric(input$chebyf), type = input$chebyt)
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})
The problem i am facing is that once the shiny app is executed , the sample data is loaded properly as the this data is placed in the app folder in the directory (one can use R inbuilt data set or use the data i gave in the start) and subsequently all steps gets executed properly.
But if i want to upload some other csv file from local directory, the upload button selection does not get activated even after selecting it.But,in fact, if one goes to the second menu item in the sidebar panel i.e. filter tab and clicks on the filter button (under Filters box ) and then if i go back to Data menu in the sidebar panel again, i can see that now my upload csv file button has got activated and now i can browse the csv file in local directory and upload the same into the app and now everything works fine.
It seems somewhere the condition that makes the upload file button is not getting active initially when the app opens....
Need help to sort out the issue...Sorry for posting large chunk of code....
conditionalPanel and submitButton do not work well together. Replace your submitButton("Filter") with actionButton("Filter", "").
EDIT:
As per the comment, for the plot to be generated only after the actionButton is clicked you can put output$dataChartFiltered inside observeEvent of Filter with isolate for `input objects as follows:
observeEvent(input$Filter,{
output$dataChartFiltered <- renderGvis({
if (isolate(input$filt) == "none") {
return(NULL)
} else if (isolate(input$filt) == "butt") {
bf <- butter(as.numeric(isolate(input$buttern)), as.numeric(isolate(input$butterf)), type = isolate(input$buttert))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(bf, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
} else if (isolate(input$filt) == "cheby2") {
ch <- cheby2(as.numeric(isolate(input$chebyn)), as.numeric(isolate(input$chebyd)),
as.numeric(isolate(input$chebyf)), type = isolate(input$chebyt))
filtered = data.frame(timestamp = dataframe()[,1],
count = as.numeric(filter(ch, dataframe()[,2])))
gvisLineChart(filtered, xvar = colnames(filtered)[1], yvar = colnames(filtered)[2],
options = list(
crosshair.trigger = 'selection',
enableInteractivity = TRUE,
hAxis.maxTextLines = 10,
tooltip.trigger = 'none'
))
}
})
})

updateCheckBoxGroupInput in shiny based on selection of other checkboxes

My shiny application has multiple tabs. In one of the tabs I have plot output which I want to use to create reports in another tab. I have included a checkbox in the first tab for the user to select the output for reporting. In the second tab I am trying to update a check box group input based on the selection of the first tab. However I am getting only the first option selected.
The reproducible code is as follows: This is based on ifelse condition:
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(
title = "MODULE",titleWidth = 225
),
dashboardSidebar(
width = 225,
sidebarMenu(id = "tabs",
menuItem("TOPLINES", tabName = "tplines", icon = shiny::icon("dashboard")),
menuItem("MY MONTHLY REPORTS", tabName = "myweeklyrep", icon = shiny::icon("compass"))
)),
dashboardBody(
tabItems(
tabItem(
tabName = "tplines",
fluidRow(
box(
checkboxInput(inputId = "inventorytop8metrocheck", "Add to reports", value = FALSE),
width = 6, status = "info", title = "Inventory information",
div(plotlyOutput("inventorytop8metro"), width = "100%", height = "400px", style = "font-size:80%;")
),
box(
checkboxInput(inputId = "top15categoriestplinescheck", "Add to reports", value = FALSE),
width = 6, status = "info", title = "Top 15 categories",
div(plotlyOutput("top15categoriestplines"), style = "font-size:90%")
))),
tabItem(
tabName = "myweeklyrep",
fluidRow(
h4("AVAILABLE ANALYSIS", align = 'center'),br(),
column(width = 12,
list(tags$div(align = 'left',
class = 'multicol',
checkboxGroupInput(inputId = 'analysisSelector',
label = "Select the analysis:",
choices = "",
selected = "",
inline = FALSE)))
))))))
server <- function(session,input,output){
observe({
updateCheckboxGroupInput(session, inputId = "analysisSelector", label = "", choices =
ifelse(!is.null(input$top15categoriestplinescheck) || length(input$top15categoriestplinescheck) != 0, "Inventory top 8 metros",
ifelse(!is.null(input$inventorytop8metrocheck) || length(input$inventorytop8metrocheck) != 0, "Top 15 categories - Topline", "No selection")),
selected = "",inline = FALSE)
})
}
shinyApp(ui,server)
I tried with if, else if also but they aren't working. Any thoughts?
The if, else if conditions:
updateCheckboxGroupInput(session, inputId = "analysisSelector", label = "", choices =
if(!is.null(input$top15categoriestplinescheck) || length(input$top15categoriestplinescheck) != 0){
"Inventory top 8 metros"
} else if (!is.null(input$inventorytop8metrocheck) || length(input$inventorytop8metrocheck) != 0){
"Top 15 categories - Topline"
} else {
return()
},
selected = "",inline = FALSE)
EDIT:
I tried the following option: which renders the checkboxes irrespective of whether they are selected or not.
getlist <- reactive({
if(!is.null(input$top15categoriestplinescheck) & !is.null(input$inventorytop8metrocheck)){
c("Top 15 categories - Topline","Inventory of top 8 metros - Topline")
} else if (!is.null(input$top15categoriestplinescheck)){
"ABC"
} else if (!is.null(input$inventorytop8metrocheck)){
"DEF"
} else {
return()
}
})
observe({
updateCheckboxGroupInput(session, inputId = "analysisSelector", label = "Select the analysis:", choices =
as.list(getlist()),
selected = "",inline = FALSE)
})
This is actually easier to handle with observeEvent as explained in the documentation of this function (see ?observeEvent). From what I understand, it actually wraps observe but in a more intuitive way.
You have to pass it two arguments: an event (in this case, the click on one of your checkboxGroupInputs) and the action to perform when this event occurs.
The server function thus becomes:
server <- function(session,input,output){
updateAnalysisSelector <- function(session) {
choices <- ifelse(input$top15categoriestplinescheck, "Inventory top 8 metros",
ifelse(input$inventorytop8metrocheck, "Top 15 categories - Topline", "No selection"))
updateCheckboxGroupInput(session,
inputId = "analysisSelector",
label = "Select the analysis:",
choices = choices,
selected = "",
inline = FALSE)
}
observeEvent(input$top15categoriestplinescheck, updateAnalysisSelector(session))
observeEvent(input$inventorytop8metrocheck, updateAnalysisSelector(session))
}
I'm sure this could be simplified if your UI did not have two separate checkbox groups but this works for your current implementation.

Resources