【问题标题】:How to select a subset of elements of the input R6 class within a shiny module to perform operations on them如何在闪亮模块中选择输入 R6 类的元素子集以对其执行操作
【发布时间】:2021-05-04 05:04:31
【问题描述】:

我能否访问一个模块中所有输入小部件的列表(让我们将其命名为myModule)并检查它们的状态是否为isTruthy()

当我知道(或可以推断)小部件的确切名称时,我找到了一种可行的方法(请参阅1)。

All_Inputs <- vapply(paste0('axis',1:3),
                     function(x) { isTruthy(input[[x]]) },
                     logical(1))

当然,我也可以用一长串if (isTruthy(input$a) &amp;&amp; isTruthy(input$b) &amp;&amp; ... 来做到这一点。但这两种解决方案对我来说都不满意,主要是因为可读性和可维护性方面的缺陷。

我知道input 类将它们全部列在以myModule-[AnyName] 开头的名称下。但我不知道如何使用这些信息通过循环甚至更好的apply 函数来访问它们。

【问题讨论】:

    标签: r shiny r6 shinymodules truthy


    【解决方案1】:

    由于input 是一个命名列表,您可以在names(input) 上使用vapply

    library(shiny)
    
    counterButton <- function(id, label = "Counter") {
      ns <- NS(id)
      tagList(
        actionButton(ns("button"), label = label),
        verbatimTextOutput(ns("out"))
      )
    }
    
    counterServer <- function(id) {
      moduleServer(
        id,
        function(input, output, session) {
          count <- reactiveVal(0)
          observeEvent(input$button, {
            count(count() + 1)
          })
          output$out <- renderText({
            count()
          })
          count
        }
      )
    }
    
    ui <- fluidPage(
      counterButton("counter1", "Counter #1"),
      counterButton("counter2", "Counter #2"),
      textOutput('istruthy')
    )
    
    server <- function(input, output, session) {
      counterServer("counter1")
      counterServer("counter2")
      output$istruthy <- renderText({ 
        vapply(names(input), 
               function(x) { 
                   ifelse(startsWith(x, "counter2-"), isTruthy(input[[x]]), TRUE) 
               },
               logical(1)) 
      })
     
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 当然! ...如果我只想在module2 中找到任何“虚假”,我可以使用命名空间来相应地过滤它们。还有一个问题:您知道如何获取 Shiny 生成的命名空间前缀吗?当然,如果可能的话,我想避免硬编码的依赖关系,ns() 只能在模块内部工作,不是吗?
    • @Jan,对于命名空间前缀,还不知道 ;)
    • 很抱歉。不想通过添加我自己的答案来窃取您的赏金。
    猜你喜欢
    • 1970-01-01
    • 2021-05-27
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2021-07-26
    • 1970-01-01
    • 2019-12-13
    相关资源
    最近更新 更多