首页 > 解决方案 > 在 Shiny 中,通过 source() 选择一个 .R 文档的 salectInput 选项,但取决于另一个 selectInput 选项的选项

问题描述

我想通过采购(source())一个.R文档来更改salectInput的选择,但取决于另一个selectInput的选择。

我尝试了不同的选项并阅读了类似的帖子,但我没有得到它的工作。

我包含了一个非常简单的 UI,其中包含我最初认为可行的代码。

对于此代码,错误是: hasGroups(choices) 中的错误:找不到对象“输入”

非常感谢您的见解。

library(shiny)


ui <- # Define UI for dataset viewer application

  shinyUI(pageWithSidebar(

    headerPanel("Input Choices"),  

    sidebarPanel(

      selectInput(inputId = "Year", "Choose a Year:", 

                  choices = c("2012", "2011")),

      selectInput(inputId = "Cat", "Choose a Category:",   
                  choices =
                    if(input$Year == "2011") {
                    source("./Choices/Choices_OpB.R")
                    } else if (input$Year == "2012"){
                      source("./Choices/Choices_OpA.R")
                    }
                  ),    width = 2),


    mainPanel(

      tabsetPanel(type = "tabs", 

                  tabPanel("Html Pages")), width = 10)

  ))

#


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

})

shinyApp(ui = ui, server = server)

Choices_OpB.R 将是:

c("D", "E", "F")

Choices_OpA.R 将是:

c("A", "B", "C")

标签: rshiny

解决方案


当然。要更改选项,我们需要在代码的服务器部分而不是 UI 中进行。updateSelectInput 函数可以为我们做这件事:

library(shiny)


ui <- shinyUI(pageWithSidebar(

    headerPanel("Input Choices"),

    sidebarPanel(

        selectInput(inputId = "Year", "Choose a Year:", choices = c("2012", "2011")),

        selectInput(inputId = "Cat", "Choose a Category:", choices = c("No Choices Yet"))

    ,width = 4),

    mainPanel(

        tabsetPanel(type = "tabs",

                    tabPanel("Html Pages")

        )

    , width = 8)

))


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

    observeEvent(input$Year, {

        if(input$Year == '2011') {source("./Choices/Choices_OpB.R")}

        if(input$Year == '2012') {source("./Choices/Choices_OpA.R")}

        updateSelectInput(session, inputId = 'Cat', label = "Choose a Category:", choices = loaded_choices)

    })

})

shinyApp(ui = ui, server = server)

为简单起见,我将 Choices_OpA.R 和 Choices_OpB.R 更改为

loaded_choices <- c("A", "B", "C")
loaded_choices <- c("D", "E", "F")

推荐阅读