0

Fairly new to shiny, trying to sort out eventReactive when updating data. In my case, I want the data.frame dat.base to not be recalculated, unless an input (textInput a2) is updated. As opposed to the stoch_data object, which should be recalculated when either of the two inputs is updated. I can't seem to sort out how to make dat.base to be created (I get the object 'dat.base' not found error any time I wrap dat.base in eventReactive.

What am I doing wrong? Thanks for any guidance...

Minimal example:

library(plyr)
library(dplyr)
library(tidyr)
library(ggplot2)

library(shiny)
library(shinydashboard)
    
sidebar <- dashboardSidebar(
    textInput(inputId = "a1", label = "First", 
                value = "10"),
                                        
    textInput(inputId = "a2", label = "Second", 
                value = "20")
)


server <- function(input, output) {
    stoch_data <- reactive({
        a1 <- as.numeric(input$a1)
        a2 <- as.numeric(input$a2)
        stoch_output <- data.frame(a1 = a1, a2 = a2)        
        }) 

    output$plot2 <- renderPlot({
        a1 <- 10
        a2 <- as.numeric(input$a2)
        
        eventReactive(input$a2, {
        dat.base <- data.frame(a1, a2) %>% 
                                                mutate(Source = "Baseline input parameters")
                                        }, ignoreNULL=FALSE)

        dat <- stoch_data() %>%
                mutate(Source = "User-provided input parameters") %>%
                rbind(dat.base) 
                
        ggplot(dat) +
            geom_point(aes(x = a1, y = a2)) +
            facet_wrap(~ Source)
        }) 
} 

body <- dashboardBody(
    mainPanel(plotOutput("plot2"), width = 350 ))

ui <- dashboardPage(sidebar = sidebar,
    body = body,
    header = dashboardHeader()
        )
                    
shinyApp(ui, server)
user2602640
  • 640
  • 6
  • 21

1 Answers1

2

You should put the eventReactive() outside the output$plot2. Try this

server <- function(input, output) {
  stoch_data <- reactive({
    a1 <- as.numeric(input$a1)
    a2 <- as.numeric(input$a2)
    stoch_output <- data.frame(a1 = a1, a2 = a2)        
  }) 
  
  dat.base <- eventReactive(input$a2, {
    a1 <- 10
    a2 <- as.numeric(input$a2)
    dat.base <- data.frame(a1, a2) %>% 
      mutate(Source = "Baseline input parameters")
  }, ignoreNULL=FALSE)
  
  output$plot2 <- renderPlot({
    
    dat <- stoch_data() %>%
      mutate(Source = "User-provided input parameters") %>%
      rbind(dat.base()) 
    
    ggplot(dat) +
      geom_point(aes(x = a1, y = a2)) +
      facet_wrap(~ Source)
  }) 
} 
YBS
  • 19,324
  • 2
  • 9
  • 27