英文:
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 <- 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?
答案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 <- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论