从 Shiny 模块中嵌套的 `selectInput` 返回值

标签 r shiny

我遇到嵌套 selectInput 的问题s 在 shiny 内模块。
考虑以下最小示例应用程序

library(shiny)

options <- list(A = 1:3, B = 4:6)

module_ui <- function(id) {
    ns <- NS(id)
    tagList(
        selectInput(ns("option1"), "Option 1", choices = LETTERS[1:2]),
        selectInput(ns("option2"), "Option 2", choices = NULL))
}
    
module_server <- function(id) {
    moduleServer(
        id,
        function(input, output, session) { 
            observe({
                updateSelectInput(
                    session, "option2", choices = options[[input$option1]])
            })
            return(list(
                option1 = reactive(input$option1),
                option2 = reactive(input$option2)))
        }
    )
}

ui <- fluidPage(
    module_ui("module"),
    textOutput("text")
)

server <- function(input, output, session) {
    sel <- module_server("module")
    output$text <- renderText({
        req(sel$option1(), sel$option2())
        print(paste0(sel$option1(), sel$option2(), collape = ""))
        paste0(sel$option1(), sel$option2(), collape = "")
    })
}

shinyApp(ui, server)
执行以下操作时可以重现我的问题:
  • 保留“选项 1”中的条目“A”和“选项 2”中的条目“1”(“选项 2”的条目基于当前从“选项 1”中选择的条目)。
  • 然后从“选项 1”中选择条目“B”。

  • 这不会立即清除和更新“选项 2”中的列表条目。相反,在短时间内,reactivemodule_server 返回值给出不存在的“选项 1”-“选项 2”组合“B1”(参见示例应用程序中的终端输出);这只会在“选项 2”中的条目通过 updateSelectInput 正确更新之前发生非常短暂的时间。 .问题是模块返回的任何不存在的值组合都会导致下游出现问题/错误。
    帖子Dealing with nested selectizeInputs and modules描述了一个非常相似的问题,但我发现在我的情况下解决方案有问题。除其他外,我希望该模块处理输入的验证。
    当我放置 selectInput 时,我没有这个问题s 在主 ui并使用 updateSelectInput在主 server .不知怎的两人reactive module_server 的返回参数中的元素是“太快了”。有没有办法验证/检查输入 在归还之前 module_server .

    最佳答案

    这是一个解决方案。您可以使用 req() 显式地进行验证。在第二个无功输出中。 IE。

    module_server <- function(id) {
      moduleServer(
        id,
        function(input, output, session) { 
          observe({
            updateSelectInput(
              session, "option2", choices = options[[input$option1]])
          })
          
          return(list(
            option1 = reactive(input$option1),
            option2 = reactive({
              req(input$option2 %in% options[[input$option1]])
              input$option2
              })))
        }
      )
    }
    
    它基本上会停止任何下游的 react ,直到条件得到满足。

    关于从 Shiny 模块中嵌套的 `selectInput` 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66096220/

    相关文章:

    r - OpenCPU数据缓存

    r - Docker中的ShinyDirButton与fileInput

    r - 计算给定核苷酸片段的核苷酸频率

    json - 在 SHINY 中显示 HTTP GET 数据

    r - busyIndi​​cator 未显示在 R shiny App 中

    r - 使用 bind_shiny() 渲染的 ggvis 图不是 react 性的

    r - 我如何添加链接以从R Shiny应用程序在新窗口中打开pdf文件?

    r - 如何在 R 中对向量的分组元素求和

    javascript - R 传单 : Assign multiple groups to a layer to filter data and change column represented

    r - 有条件地乘以向量(货币换算)