简体   繁体   中英

Create reactive data frame dependent on selected tabItem

In my shinyApp i have a Data Frame which i want it to be reactive dependent on the Tab that is selected. I tried the following, but it does not work. Any other ideas?

library(shiny)
library(shinydashboard)
library(tidyverse)

data = tibble(colOne=c(1:10), colTwo=c(rep(1, 5), rep(2, 5)))

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(
  
  sidebarMenu(
    menuItem(text = "Name for first Tab", tabName = "start"),
    menuItem(text = "Name for second Tab", tabName = "1"),
    menuItem(text = "Name for third Tab", tabName = "2")
  )
)

body = dashboardBody(
          
  tabItems(   
  tabItem(tabName = "start"),
  tabItem(tabName = "1"),
  tabItem(tabName = "2")))

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){
  
reactive_data = reactive({
    data %>% filter(colTwo == input$tabName)
}

shinyApp(ui, server)

You can add an id to your sidebarMenu . Then, this can be used for resulting changes in menu selected. This should be a working example:

library(shiny)
library(shinydashboard)
library(tidyverse)

data = tibble(colOne=c(1:10), colTwo=c(rep(1, 5), rep(2, 5)))

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(
  sidebarMenu(id = "tab", 
    menuItem(text = "Name for first Tab", tabName = "start"),
    menuItem(text = "Name for second Tab", tabName = "1"),
    menuItem(text = "Name for third Tab", tabName = "2")
  )
)

body = dashboardBody(
  tabItems(   
    tabItem(tabName = "start"),
    tabItem(tabName = "1"),
    tabItem(tabName = "2")))

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){
  
  observe({
    print(reactive_data())
  })
  
  reactive_data <- reactive({
    data %>% 
      filter(colTwo == input$tab)
  })
  
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM