Search code examples
rshinyggvis

Use reactive function as ggvis input


I have a Shiny app that uses a CSV as input and load when a button is pressed.

 shinyServer(function(input, output) {

  dataInput <- reactive({
    if(is.null(input$file)) {
      return(NULL)
    }
    butt$a
  })

  butt <- reactiveValues()

  observe({
    if (input$goButton == 0) {
      butt$a <- return(NULL)
    }
    if (input$goButton > 0) {
      butt$a <- read.csv(input$file$datapath, 
                         header = input$header, 
                         sep = input$sep, quote = input$quote)
    }
  })

And I would like to use dataInput() as an input for a ggvis plot:

  output$ggvisplot_ui <- renderUI({
    if(is.null(butt$a)) {
      return(NULL)
    }
    ggvisOutput("ggvisplot")
  })

  reactive({
  dl <- dataInput()
  dl %>%
    ggvis(~mpg, ~wt) %>% 
    layer_points() %>% 
    bind_shiny("ggvisplot")
  })

Here my CSV input is mtcars.csv so I use ~mpg and ~wt as columns. If I take out the reactive({ }) part replace dl <- dataInput() with dl <- mtcars it works just fine:

  output$ggvisplot_ui <- renderUI({
    if(is.null(butt$a)) {
      return(NULL)
    }
    ggvisOutput("ggvisplot")
  })

  dl <- mtcars
  dl %>%
    ggvis(~mpg, ~wt) %>% 
    layer_points() %>% 
    bind_shiny("ggvisplot")

Solution

  • This works:

      output$ggvisplot_ui <- renderUI({
        if(is.null(butt$a)) {
          return(NULL)
        }
        ggvisOutput("ggvisplot")
      })
    
      observe({
        if (!is.null(butt$a)) {
          dl <- dataInput()
          dl %>%
            ggvis(~mpg, ~wt) %>% 
            layer_points() %>% 
            bind_shiny("ggvisplot")
        }
      })