定期切换shinydashboard中的标签

时间:2017-09-30 16:05:33

标签: r shiny

shinydashboard中有多个标签,例如此处

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Sample Shiny"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Tab 1", tabName = "tab1"),
      menuItem("Tab 2", tabName = "tab2")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        "tab1",
        fluidRow(
          box(title = "Foo")
        )
      ),
      tabItem(
        "tab2",
        fluidRow(
          box(title = "Bar")
        )
      )
    )
  )
)

server <- function(input, output) { }

shinyApp(ui = ui, server = server)

是否可以让应用程序定期切换活动标签?我想让我的屏幕上的仪表板每隔x分钟切换一次活动标签。

我已经检查了Shiny文档的解决方案,但还没有找到合适的功能。但也许我只是忽略了这样一个功能。如果Shiny没有提供合适的功能,是否可以包含一些可以完成这项工作的自定义JavaScript?

1 个答案:

答案 0 :(得分:2)

这是一种使用invalidateLater和updateTabItems的方法:

app.R:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Sample Shiny"),
  dashboardSidebar(
    sidebarMenu(
      id = 'tabs',
      menuItem("Tab 1", tabName = "tab1"),
      menuItem("Tab 2", tabName = "tab2")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        "tab1",
        fluidRow(
          box(title = "Foo")
        )
      ),
      tabItem(
        "tab2",
        fluidRow(
          box(title = "Bar")
        )
      )
    )
  )
)

tabnames = c('tab1', 'tab2')
server <- function(input, output, session) {
  #keep track of active tab
  active <- reactiveValues(tab = 1)

  observe({
    #Change every 5 secs, you can set this to whatever you want
    invalidateLater(5000,session)
    #update tab
    isolate(active$tab <- active$tab%%length(tabnames) + 1)
    updateTabItems(session,'tabs',tabnames[active$tab])
  })
}

shinyApp(ui = ui, server = server)