agf1997
agf1997

Reputation: 2898

Avoiding code duplication in Shiny Reactive Expressions

I'm new to Shiny so forgive me if this question is misguided.

Say I have 2 separate inputs input$n_1 and input$n_2 that invoke nearly identical code.

library(shiny)

ui <- fluidPage(
  fluidRow(
    numericInput("n_1", label = "n1", value = 5000),
    numericInput("n_2", label = "n2", value = 5000),
    textOutput("result1"),
    textOutput("result2")
  )
)

server <- function(input,output,session)({

  generate_result1 <- reactive({
    # A whole lot of code to generate a result using input$n_1
    x = input$n_1 * 5
  })

  generate_result2 <- reactive({
    # A whole lot of identical code to generate a result using but using input$n_2.  
    # This example only shows one line of code but the real code has dozens of  
    # lines of code where the only difference from generate_result1 is that it uses 
    # input$n_2 instead of input$n_1.
    x = input$n_2 * 5
  })

  output$result1 <- renderText(generate_result1())
  output$result2 <- renderText(generate_result2())

})

shinyApp(ui = ui, server = server)

Is there a way to avoid the code duplication currently found in generate_result1 and generate_result2 in the example above?

Upvotes: 1

Views: 218

Answers (1)

Sal-laS
Sal-laS

Reputation: 11649

As i understand the process of obtaining generate_result1, and generate_result2, are very similar. The only difference is they receive different inputs.

In this case, you should write a function and pass the inputs to it

generate_result<- function(input){
  # bla bla bla
   reactive( final_result)  
}

and then call it based on different inputs, as below:

server <- function(input,output,session)({


  output$result1 <- renderText({generate_result(input$n_1)})
  output$result2 <- renderText({generate_result(input$n_2)})

})

Upvotes: 1

Related Questions