Hi everyone,
Here is a simplified code of an app I am working on.
There is a slider where an initial value will be applied depending on the country selected.
The user can of course move the slider but if that's the case, i want the texts below to be updated.
At the moment, the app works as i want it work but i feel my code could be much simpler. I was initially looking for something like 'As soon as the user moves the slider, the texts below must change'. But i couldn't find a way other than using the logic that compares the initial value by default and the value currently on the slider.
There must be something to do with the reactive values or the observeEvents but i couldn't quite figure it out.
Any thoughts?
library(shiny)
library(shinyjs)
library(dplyr)
Data<-data.frame(Countries=c('A','B','C','D','E','F'),
Totals=c(5,6,8,9,18,55),
Date=as.Date(c('2021-07-14','2021-07-14','2021-07-12','2021-07-13','2021-07-14','2021-07-14')))
ui <- fluidPage(
selectInput(
'Country',
'Select the country',
unique(Data$Countries),
selected = NULL,
multiple = FALSE,
selectize = TRUE,
width = NULL,
size = NULL
),
actionButton("reset_input", "Reset values to default"),
useShinyjs(),
uiOutput("slider_totals"),
textOutput("TotalsText"),
textOutput("SourceText"),
textOutput('DatesText'),
)
# Define server logic required to draw a histogram
server <- function(input, output,session) {
value_slider_default<-reactive({
(Data %>% filter(Countries==input$Country))$Totals
})
#
Totals<-reactive({
if (input$myslider==value_slider_default()){
paste0('Totals = ',value_slider_default())
}
else {
paste0('Totals = ',input$myslider)}
})
output$TotalsText<-renderText({
Totals()
})
observeEvent(input$reset_input, {
reset("slider_totals")
})
Source<-reactive({
if (input$myslider==value_slider_default()){
paste0('Source = Official')
}
else {
paste0('Source = User')}
})
output$SourceText<-renderText({
Source()
})
enddate<-reactive({
(Data %>% filter(Countries==input$Country))$Date
})
startdate<-reactive({
(Data %>% filter(Countries==input$Country))$Date - 14
})
Dates<-reactive({
if (input$myslider==value_slider_default()){
paste0('Timeframe =',startdate(),' -> ',enddate())
}
else {
'Timeframe = Unknown'
}
})
output$DatesText<-renderText({Dates()})
output$slider_totals <- renderUI({
sliderInput("myslider", "Totals", value=value_slider_default(),min= 0, max=60)
})
}
# Run the application
shinyApp(ui = ui, server = server)