I am new to shiny, and am making an app where a user adjusts 3 sliders. Output is the total change of the 3 sliders in % form, and the difference from the initial form.
I added a 'reset' button so that I can change the sliders all back to 0, but it is not working.
I tried looking R shiny: reset plot to default state, and Reset inputs with reactive app in shiny, to no avail. I tried a piece of code:
observeEvent(input$reset,{
input$Var1=0
return(input$Var1)
})
to adjust a single slider and set it to 0, then return this value, also to no avail. Any suggestions?
My full code is :
library(shiny)
ui=fluidPage(
titlePanel("Sum of Sliders"),
fluidRow(
column(2,
sliderInput("Var1", "Slider1:",
min = -100, max = 100,
value = 0),
sliderInput("Var2", "Slider2:",
min = -100, max = 100,
value = 0),
sliderInput("Var3", "Slider3:",
min = -100, max = 100,
value = 0),
submitButton("Submit"),
actionButton("reset", "Reset")
),
column(6,
verbatimTextOutput("text"),
verbatimTextOutput("text2"),
verbatimTextOutput("change")
)
)
)
server=function(input, output) {
observeEvent(input$reset,{
input$Var1=0
return(input$Var1)
})
output$text <- renderText({
paste("Starting Value:", 0)
})
output$text2= renderText({
v=rep(0,3)
v[1]= input$Var1/100
v[2]= input$Var2/100
v[3]= input$Var3/100
paste("Slider Sum:", sum(v))
})
output$change <- renderText({
paste("Difference is:", output$text2-output$text)
})
}
shinyApp(ui, server)
To change an existing input, you can use updateSliderInput
. Also, since you included a submitButton
, I assume you want the changes to only apply when you click that button. It is probably easiest to use reactiveVal
's to get the desired behavior. A working example is given below, creating output$change
is left as an exercise to the reader ;) hope this helps!
library(shiny)
ui=fluidPage(
titlePanel("Sum of Sliders"),
fluidRow(
column(2,
sliderInput("Var1", "Slider1:",
min = -100, max = 100,
value = 0),
sliderInput("Var2", "Slider2:",
min = -100, max = 100,
value = 0),
sliderInput("Var3", "Slider3:",
min = -100, max = 100,
value = 0),
actionButton('submit','Submit'),
actionButton("reset", "Reset")
),
column(6,
verbatimTextOutput("text"),
verbatimTextOutput("text2")
)
)
)
server=function(input, output, session) {
observeEvent(input$reset,{
updateSliderInput(session,'Var1',value = 0)
updateSliderInput(session,'Var2',value = 0)
updateSliderInput(session,'Var3',value = 0)
})
rv_text1 <- reactiveVal()
rv_text2 <- reactiveVal()
observeEvent(input$submit,{
rv_text1(paste("Starting Value:", 0))
v=rep(0,3)
v[1]= input$Var1/100
v[2]= input$Var2/100
v[3]= input$Var3/100
rv_text2(paste("Slider Sum:", sum(v)))
})
output$text <- renderText({rv_text1()})
output$text2 <- renderText({rv_text2()})
}
shinyApp(ui, server)