根据shinydashboard中选定的选项卡更改元素的值

时间:2016-08-08 21:09:59

标签: r shiny shinydashboard

我尝试使用shinydashboard创建应用,其中有一个响应元素,根据选择的标签更改值。以下是我在app.R文件中获得的代码。有一个if / else语句目前已注释掉我希望能够使用。 if / else语句将根据选择的选项卡更改answer的值。

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title='Title'),
  dashboardSidebar(
    sidebarMenu(
      menuItem('Models', tabName='Models',
        menuSubItem('Model1', tabName='Model1'),
        menuSubItem('Model2', tabName='Model2')
      ),
      tags$head(tags$script(HTML('$(document).ready(function() {$(".treeview-menu").css("display", "block");})')))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName='Model1',
        h1("Model 1"),
        verbatimTextOutput('out1')
      ),
      tabItem(tabName='Model2',
        h1("Model 2"),
        verbatimTextOutput('out2')
      )
    )
  )
)

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

  answer <- reactive({
    #if(selected tabName=='Model1'){
      answer <- 1
    #} else if(selected tabName=='Model2'){
      answer <- 2
    #}
    return(answer)
  })

  output$out1 <- renderPrint(answer())
  output$out2 <- renderPrint(answer())
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:3)

对此的解决方案实际上非常简单且非常优雅。您必须sidebarMenu IDtab,而input$tab将报告选择了哪个标签。

因此,您的if-else语句将如下所示:

if (input$tab == 'Model1'){
      answer <- 1
    } else if (input$tab == 'Model2'){
      answer <- 2
    }

完整示例:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title='Title'),
  dashboardSidebar(
    sidebarMenu(id = "tab", # added ID 
      menuItem('Models', tabName='Models',
               menuSubItem('Model1', tabName='Model1'),
               menuSubItem('Model2', tabName='Model2')
      ),
      tags$head(tags$script(HTML('$(document).ready(function() {$(".treeview-menu").css("display", "block");})')))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName='Model1',
              h1("Model 1"),
              verbatimTextOutput('out1')
      ),
      tabItem(tabName='Model2',
              h1("Model 2"),
              verbatimTextOutput('out2')
      )
    )
  )
)

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

  observe({
    print(input$tab)
  })

  answer <- reactive({
    if (input$tab == 'Model1'){
      answer <- 1
    } else if (input$tab == 'Model2'){
      answer <- 2
    }
    return(answer)
  })

  output$out1 <- renderPrint(answer())
  output$out2 <- renderPrint(answer())
}

shinyApp(ui, server)