如何动态分配响应对象的名称?

huangapple go评论82阅读模式
英文:

How to dynamically assign the name of a reactive object?

问题

我有一个生成多个表格的应用程序,它们的ID仅在末尾附加的数字不同。虽然我目前复制并粘贴大部分代码来创建所有这些面板,如下所示:

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

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

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

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

我想使用lapply或任何其他函数使代码更具动态性,以便使我的代码更易于阅读。我应该如何做?

英文:

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 &lt;- reactive({panelData(1, input$hsyear1, input$panel1range)})

  output$panel1plot &lt;- renderPlot({panelPlot(panel1Data(), 1)})

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

  output$panel2plot &lt;- 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?

答案1

得分: 1

你没有提供一个可复现的示例,所以我无法进行测试。我会这样做:

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)
  })
})

如果这不起作用,请提供一个可复现的示例。

英文:

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

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

lapply(1:2, function(i){
  id &lt;- sprintf(&quot;panel%dplot&quot;, i)
  output[[id]] &lt;- renderPlot({
    panelPlot(panelsData[[i]](), i)
  })
})

Please provide a reproducible example if that does not work.

huangapple
  • 本文由 发表于 2020年1月6日 23:33:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定