gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:29:14 26 4
gpt4 key购买 nike

我遇到嵌套 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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com