闪亮的renderUI仅显示最后的输出

时间:2018-10-04 12:30:45

标签: r dynamic shiny

我正在尝试使用renderUIuiOutput通过for循环动态创建一些内容,但是每个呈现的元素仅包含来自for循环中最后一次迭代的信息。示例:

require(shiny)
ui <- fluidPage(
  uiOutput("out1"),
  uiOutput("out2")
)

server <- function(input, output, session) {
  count <- 1
  for(a in c("hello", "world")){
    name <- paste0("out", count)
    output[[name]] <- renderUI({
      strong(a)
    })
    count <- count + 1
  }
}
shinyApp(ui = ui, server = server)

这两次输出 world ,而不是 hello world

2 个答案:

答案 0 :(得分:2)

它在使用sapply而不是for循环时有效:

require(shiny)

ui <- fluidPage(
  uiOutput("out1"),
  uiOutput("out2")
)

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

  vec <- c("hello", "world")

  sapply(seq_along(vec), function(x) {
    name <- paste0("out", x)
    output[[name]] <- renderUI({
      strong(vec[x])
    })
  })

}

shinyApp(ui = ui, server = server)

答案 1 :(得分:2)

由于亚历山大(Zygmunt Zawadzki)的评论,我发现使用local({})可以替代亚历山大的答案,

ui <- fluidPage(
  uiOutput("out1"),
  uiOutput("out2")
)

server <- function(input, output, session) {
  count <- 1
  for(a in c("hello", "world")){
    local({
      b <-a #this has to be added as well
      name <- paste0("out", count)
      output[[name]] <- renderUI({
        strong(b)
      })
    })
    count <- count + 1
  }
}
shinyApp(ui = ui, server = server)