0

I have an app that generates several tables whose id's only differ by a suffixed number. While I currently copy and paste most of my code to create all these panels like so:

  #  Panel 1
  panel1Data <- reactive({panelData(1, input$hsyear1, input$panel1range)})

  output$panel1plot <- renderPlot({panelPlot(panel1Data(), 1)})

  #  Panel 2
  panel2Data <- reactive({panelData(2, input$hsyear2, input$panel2range)})

  output$panel2plot <- renderPlot({panelPlot(panel2Data(), 2)})

I want to use lapply or any other function to make this more dynamic so that I can make my code a bit easier on the eye. How would I go about doing this?

ANam
  • 337
  • 2
  • 15
  • 1
    Most likely you'd want to use a `reactiveValues()` list rather than a bunch of separate `reactiveVal` objects. But it would be easier to confirm that if you provided a minimal [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that could be used for testing. – MrFlick Jan 06 '20 at 15:38
  • Agreed with @MrFlick. You can use character variables to dynamically assign names to a reactiveValues list. Also this seems like a good opportunity to leverage shiny modules. – SmokeyShakers Jan 06 '20 at 15:40

1 Answers1

1

You don't provide a reproducible example so I can't test. I would do something like that:

panelsData <- lapply(1:2, function(i){
  hsyear <- paste0("hsyear", i)
  panelrange <- sprintf("panel%drange", i)
  reactive({
    panelData(i, input[[hsyear]], input[[panelrange]])
  })
})

lapply(1:2, function(i){
  id <- sprintf("panel%dplot", i)
  output[[id]] <- renderPlot({
    panelPlot(panelsData[[i]](), i)
  })
})

Please provide a reproducible example if that does not work.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225