问题描述
我能否访问一个模块中所有输入小部件的列表(让我们将其命名为 myModule
)并检查它们的状态是否为 isTruthy()
。
当我知道(或可以推断)小部件的确切名称时,我找到了一种有效的方法(请参阅 1)。
All_Inputs <- vapply(paste0('axis',1:3),function(x) { isTruthy(input[[x]]) },logical(1))
当然,我也可以使用一长串 if (isTruthy(input$a) && isTruthy(input$b) && ...
来完成。但是这两种解决方案我都不满意,主要是因为在可读性和可维护性方面存在缺陷。
我知道 input
类将它们全部列在以 myModule-[AnyName]
开头的名称下。但我不知道如何使用这些信息通过循环甚至更好的 apply
函数来访问它们。
解决方法
由于 input
是命名列表,您可以在 vapply
上使用 names(input)
:
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,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)