首页 > 解决方案 > Shiny:从目的地渲染动态数量的图像

问题描述

我需要从目的地渲染动态数量的图像。但作为通过循环的结果,我只渲染了来自目的地的最后一张图像。但所有图像都必须不同。

我的解决方案受到来自 stackoverflow 的这些答案的启发

Shiny:输出元素/绘图的动态数量

使用闪亮动态地将绘图添加到网页

library(shiny)

# get all files from destination
images <- list.files("charts")
image_names <- str_replace_all(images, ".png", "")


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


  output$images <- renderUI({

    image_output_list <- 
      lapply(1:length(image_names),
             function(i)
             {
               imagename = paste0(image_names[i], "_image")
               imageOutput(imagename)             

             })

    do.call(tagList, image_output_list)
  })

  observe({
    # if(is.null(input$files)) return(NULL)
    for (i in 1:length(image_names))
    {
      print(i)
      local({
        imagename <- paste0(image_names[i], "_image")
        print(imagename)
        output[[imagename]] <- 
          renderImage({
            list(src = normalizePath(paste0('charts/', image_names[i], '.png')))
          }, deleteFile = FALSE)
      })
    }
  })

})

ui <- shinyUI(fluidPage(
  titlePanel("Sidebar"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      uiOutput('images')
    )
  )
))

shinyApp(ui=ui,server=server)

标签: rshinyrstudio

解决方案


你能试试这个:

  observe({
    for (i in 1:length(image_names))
    {
      local({
        ii <- i
        imagename <- paste0(image_names[ii], "_image")
        print(imagename)
        output[[imagename]] <- 
          renderImage({
            list(src = normalizePath(paste0('charts/', image_names[ii], '.png')))
          }, deleteFile = FALSE)
      })
    }
  })

推荐阅读