rshinyshinydashboarddo.call

How to implement a dynamic number of slides using shinydashboardPlus' carousel?


I wish to use shinydashboardPlus' carousel to display a number of charts. The number of these charts can vary on a daily basis from one to ten.

A cron job runs the R script daily.

Here is a working example with a fixed number of slides, three.

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)

chart_names <- c( "http://placehold.it/900x500/39CCCC/ffffff&text=Slide+1", 
                  "http://placehold.it/900x500/39CCCC/ffffff&text=Slide+2",
                  "http://placehold.it/900x500/39CCCC/ffffff&text=Slide+3")


ui <- dashboardPagePlus(

  header = dashboardHeaderPlus(disable = TRUE ),
  sidebar = dashboardSidebar(width = 0 ),

 
  body = dashboardBody(
    carousel(indicators = TRUE,
             id = "mycarousel",
             carouselItem(
               tags$img(src = chart_names[1])
             ),
             carouselItem(
               tags$img(src = chart_names[2])
             ),
             carouselItem(
               tags$img(src = chart_names[3])
             )
    )
  )
)

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

shinyApp(ui, server)

Is this an example of where do.call could be used?

constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

This attempt:

do.call(carousel, as.list(c(id = "mycarousel", "carouselItem(tag$img(src = chart_names[1])")))

results in this error:

Error: $ operator is invalid for atomic vectors

How do I programmatically add a previously unknown number of slides to a shinydashboardPlus carousel?


Solution

  • The answer was in the doc with the .list parameter ?carousel

    library(shiny)
    library(shinydashboard)
    library(shinydashboardPlus)
    
    nb_items = 5
    
    items = Map(function(i) {carouselItem(
      tags$img(src = paste0("http://placehold.it/900x500/39CCCC/ffffff&text=Slide+", i))
    )}, 1:5)
    
    
    ui <- dashboardPagePlus(
      
      header = dashboardHeaderPlus(disable = TRUE ),
      sidebar = dashboardSidebar(width = 0 ),
      
      
      body = dashboardBody(
        carousel(indicators = TRUE,
                 id = "mycarousel",
                 .list = items
        )
        
      )
    )
    
    server <- function(input, output, session) {}
    
    shinyApp(ui, server)