Run
Run

Reputation: 57286

R Shiny - how to share variables between Rendering functions?

I have variables that I get from ui.R and I want to use them in renderUI and renderPlot functions such as below,

shinyServer(

  function(input, output, session) {

  output$text <- renderUI({

      # Sites.
      site1 = input$site1
      site2 = input$site2
      site3 = input$site3
      site4 = input$site4

    })

    output$plot = renderPlot({

      # Sites.
      site1 = input$site1
      site2 = input$site2
      site3 = input$site3
      site4 = input$site4

    })

})

I have to repeat the variables twice, is there any way I can put them in one place and share them between the functions? I will get error if I put the variables outside these functions.

Any ideas?

Upvotes: 2

Views: 2496

Answers (1)

karirogg
karirogg

Reputation: 128

You could create another reactive function that returns a list, like this:

shinyServer(
  function(input, output, session) {

    site <- reactive({
      unlist(list("site1" = input$site1, 
                  "site2" = input$site2, 
                  "site3" = input$site3, 
                  "site4" = input$site4))
    }

    output$text <- renderUI({
         site = site()
    })

    output$plot = renderPlot({
         site = site()
    })
})

Then you can call site1 by simply doing site[1].

Hope this helps!

Upvotes: 6

Related Questions