1
votes

I am new to Shiny, so excuse if this is trivial...

I have a server() function that outputs several plots. The plots use the same block of code and each adds some of its own, like this:

shinyServer( function( input, output ){
output$plot1 <- renderPlot({
  the block of the same code
  some code specific to plot1
})
output$plot1 <- renderPlot({
  The block of the same code
  some code specific to plot2
})

I want to avoid repeating "the block of the same code". This has to be in the renderPlot function since it takes changeable data from the UI function.

1

1 Answers

1
votes

You'll want to put the block into a "reactive" - like a function, but it reacts to changes.

shinyServer( function( input, output ){
  basicplot = reactive({
                 the block of the same code
              })
output$plot1 <- renderPlot({
  plot1 = basicplot()
  some code specific to plot1
})
output$plot2 <- renderPlot({
  plot2 = basicplot()
  some code specific to plot2
})

the "basicplot" reactive is basically a function that outputs whatever it is that the plot1 and plot2 specific parts need to work on.