Reputation: 147
What I have learnt from the differences between the ADD and REMOVE Button.
As we can see from the codes below, the main difference is how the ADD and REMOVE buttons affect the scenarios line. The REMOVE button effectively uses the scenarios[-length(scenarios)]
command to remove the immediate last scenario while keeping the other codes constant with the ADD button.
A very simple one-line code solution, and yet elegant approach to solve the problem. I learned alot again. Thank you all.
observeEvent(input$add, {
if (!(shock %in% scenarios)) {
scenarios <<- sort(c(scenarios, shock))
updateCheckboxGroupInput(session, "scenarios",choices = scenarios,selected = scenarios)
}
observeEvent(input$remove,{
scenarios <<- scenarios[-length(scenarios)]
updateCheckboxGroupInput(session, "scenarios",choices = scenarios,selected = scenarios)
})
Upvotes: 1
Views: 319
Reputation: 29387
This should do:
library(shiny)
ui <- fluidPage(
numericInput("shock", "Shock", value = round(runif(1) * 1000), 0),
actionButton("add", "Add"),
actionButton("remove", "Remove"),
checkboxGroupInput("scenarios", "Scenarios", choices = c(), selected = c()),
verbatimTextOutput("o1")
)
scenarios <- c(-100, -50, 0, 50, 100)
server <- function(input, output, session) {
updateCheckboxGroupInput(session, "scenarios",
choices = scenarios,
selected = scenarios)
observeEvent(input$add,{
shock <- isolate(input$shock)
if (!(shock %in% scenarios)) {
scenarios <<- sort(c(scenarios, shock))
updateCheckboxGroupInput(session, "scenarios",choices = scenarios,selected = scenarios)
}
# put a new random value
updateNumericInput(session, "shock", value = round(runif(1) * 1000))
})
observeEvent(input$remove,{
scenarios <<- scenarios[-length(scenarios)]
updateCheckboxGroupInput(session, "scenarios",choices = scenarios,selected = scenarios)
})
output$o1 <- renderPrint({
x <- input$scenarios
str(x)
cat(paste0("length: ", length(x), "\n"))
cat(paste0(x, "\n"))
})
}
shinyApp(ui, server)
Upvotes: 1