首页 > 解决方案 > 模块化具有多个输出 ID 的闪亮代码

问题描述

我在 Shiny 应用程序中有许多 outputID:

在下面的示例中,我只有三个 outputID

SERVER:
outIDs <- paste("text",1:3) 

lapply(list("text1", "text2", "text3"), function(x){

  output[[x]] <- renderText({
    switch(x,
          "text1" = "This is text 1",
          "text2" = "This is text 2",
          "text3" = "This is text 3"
           )
     })
    })

UI:
 lapply(outIDs), function(x) htmlOutput(x))

它可以渲染,但是如果我有 30 个,那么压缩代码的最佳方法是什么?我试过这个

SERVER:
outIDs <- paste("text", 1:30) 
outText<- paste("This is test", 1:30)

 for (i in 1: length(outIDs ){
output[[outIDs[i]]] <- renderText({
outText[i]
  })

UI:
 lapply(outIDs), function(x) htmlOutput(x))

通过上述方法,它呈现这个:

“这是文本 30” “这是文本 30”

.... 30 次。

相反,我想要:

“这是文本 1”。“这是文本 2” ... “这是文本 30”

感谢您的帮助,谢谢!

标签: rshiny

解决方案


请参阅以下内容(使用lapply而不是 for 循环):

library(shiny)

outIDs <- paste("text", 1:30)
outText <- paste("This is test", 1:30)

ui <- fluidPage(lapply(outIDs, function(x)
  htmlOutput(x)))

server <- function(input, output, session) {
  lapply(seq_along(outIDs), function(i) {
    output[[outIDs[i]]] <- renderText({
      outText[i]
    })
  })
}

shinyApp(ui, server)

作为替代方案,您可以使用它local({ })来使循环工作(请参阅以下链接)。 在这里,您可以找到有关闪亮的反应和循环的一些信息。

在示例 3 中,Joe Cheng 解释了有关 for 循环的行为如下:

# --- Joe on this behavior:
# --- > It's because all the iterations of the for loop share the same
# --- > reference to el. So when any of the created reactive expressions 
# --- > execute, they're using whatever the final value of el was.

推荐阅读