Home Ask Login Register

Developers Planet

Your answer is one click away!

user1478354 February 2016

How to avoid code duplication in a render() function in Shiny for R

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.

Answers


CPhil February 2016

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.

Post Status

Asked in February 2016
Viewed 3,919 times
Voted 12
Answered 1 times

Search




Leave an answer


Quote of the day: live life