Quantcast
Channel: In R Shiny, how to implement a reactive function? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

In R Shiny, how to implement a reactive function?

$
0
0

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:

  • Image 1: Default view when first invoking the App. Scenario 1 isautomatically generated, of 10 random samples (number of samples plotted on x-axis, random numbers on y-axis). 10 is the default value for number of samples. So far so good.
  • Image 2: Next step: I moved the input slider to 6 (without touching the action button), and scenario 1 remains at 10 samples. I'd like scenario 1 to reactively re-run for 6 samples, not the default 10.
  • Image 3: Next step after the above: shows how all else works fine, when clicking the "Add scenario" action button. I move the slider and new scenarios are generated based on the value of the input slider.

(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)

enter image description here

enter image description here

enter image description here


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images