In the below MWE code, I'd like a change in the slider input for number of scenarios to reactively change the scenario 1 that is first rendered (before clicking the "Add scenario" action button). Once another scenario is added by clicking the action button (scenarios 2, 3, etc.), the scenario 1 would remain where it was when slider input was changed. The images shown at the bottom should better explain:
(Btw don't worry about a blank modal dialog being triggered by this action button -- I need it for later purposes).
Can anyone help make that slider input reactive for scenario 1?
Note that as it currently works, when clicking "Add scenario", prior slider inputs for the scenario runs correctly "gel" (don't change).
MWE code:
library(shiny)
library(tidyverse)
library(ggplot2)
ui <- fluidPage(
sliderInput('samples','Number of samples (X):',min=2,max=10,value=10),
actionButton("add", "Add scenario"),
plotOutput("plot"),
)
server <- function(input, output, session) {
v <- reactiveValues(results=tibble(Scenario=1, X=1:10, Y=runif(10)))
observeEvent(req(input$periods), {
v <- reactiveValues(results=tibble(Scenario=1,X=1:input$samples,Y=input$samples))
})
observeEvent(input$add, {showModal(modalDialog(footer = modalButton("Close")))
newData <- tibble(Scenario=max(v$results$Scenario)+1,X=1:input$samples,Y=runif(input$samples))
v$results <- v$results %>% bind_rows(newData)
})
output$plot <- renderPlot({
v$results %>% ggplot() + geom_line(aes(x=X, y=Y, colour=as.factor(Scenario)))
})
}
shinyApp(ui, server)
See if this works. ideally you should use map_dfr or some such function to generate the tibble. But to make the code easily understandable I just used a for loop.
library(shiny)
library(tidyverse)
library(ggplot2)
ui <- fluidPage(
sliderInput('samples','Number of samples (X):',min=2,max=10,value=10),
actionButton("add", "Add scenario"),
plotOutput("plot"),
)
server <- function(input, output, session) {
numScenarios <- reactiveValues(numS=1)
observeEvent(input$add, {showModal(modalDialog(footer = modalButton("Close")))
numScenarios$numS <- (numScenarios$numS+1)
})
output$plot <- renderPlot({
v <- tibble()
for (i in 1: numScenarios$numS){
results=tibble(Scenario=i,X=1:input$samples,Y=runif(input$samples))
v <- bind_rows(v, results)
}
v %>% ggplot() + geom_line(aes(x=X, y=Y, colour=as.factor(Scenario)))
})
}
shinyApp(ui, server)