You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny基于过滤列表动态生成图片轮播的实现问题

Shiny Dashboard动态生成图片轮播的解决方法

原始代码存在3处可修正的问题:

  • 未加载dplyr包,调用filter()函数会直接报错
  • 生成轮播项时未正确遍历过滤后的图片列表,导致轮播内容为空
  • 测试用的本地图片路径替换为在线可访问地址即可直接运行验证

以下是可直接运行的完整修正代码:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(DT)
library(shinyWidgets)
library(dplyr)

df <- data.frame(
  name = c("rose", "carnation", "hydrangea"),
  color = c("red", "pink", "blue"),
  Picture = c("https://i.sstatic.net/EcA0k.jpg", 
              "https://i.sstatic.net/L0gI9.jpg", 
              "https://i.sstatic.net/2NiEh.jpg")
)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic Carousel", 
                  titleWidth =300
                  
  ),
  
  dashboardSidebar(width = 300,
                   
                   pickerInput(inputId = "color", 
                               label = "Options",
                               pickerOptions(width = "fit"),
                               choices = df$color, 
                               selected = df$color,
                               multiple = TRUE,
                               options = pickerOptions(actionsBox = TRUE, dropupAuto = FALSE))
                   
  ),
  dashboardBody(
    fluidRow(width = 6,
             
             uiOutput("carousel")
             
    ),
    
    fluidRow(width = 12,
             dataTableOutput("table")
    )
  )
)

server <- function(input, output) {
  
  filtered <- reactive({
    df %>%
      filter(color %in% input$color)
  })
  
  output$carousel <- renderUI({
    req(nrow(filtered()) > 0)
    # 生成轮播项
    items <- lapply(filtered()$Picture, function(img_url) {
      carouselItem(
        tags$img(src = img_url, width = "100%")
      )
    })
    # 生成轮播组件
    carousel(indicators = TRUE,
             id = "carousel",
             .list = items
    )
    
  })
  
  output$table <- renderDT(filtered())
  
}

shinyApp(ui = ui, server = server)

代码运行后,选择侧边栏的颜色筛选选项,轮播组件会自动更新为匹配筛选条件的图片,下方表格也会同步展示筛选后的数据。

内容的提问来源于stack exchange,提问作者Melissa Salazar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:15:08