r语言 - 我在闪亮的应用程序中使用复选框组输入遇到一些意外行为



我是Shiny的新手 - 很多我还不完全理解。 我正在开发一个闪亮的应用程序来显示一些数据。 我想允许在绘制数据之前对数据进行可选的过滤。 为了构造我的条件,UI 将提供一些selectInput。 我的计划是最初禁用这些。 我可以在UI中添加按钮以独立激活每个selectInput。 但我想尝试使用checkboxGroupInput来完成这项任务。 为了开始开发它,我尝试只处理一个checkboxGroupInput值,只启用/禁用其中一个selectInput。 除了一种特定情况外,它运行良好。 如果我选择目标checkboxGroupInput,则目标selectInput将启用。 但是,如果我取消选择该目标checkboxGroupInput,则目标selectInput不会被禁用。 但是,仅当当前未选择其他checkboxGroupInput时,才会发生此行为。 如果选择了任何或多个其他checkboxGroupInput,则目标将根据我对代码的(有限)理解,以我想要和期望的方式启用和禁用。

下面是(希望)一段清晰简单的代码来演示这种行为。 我有一个checkboxGroupInput,有四个项目,4个selectInput。 选中第三个checkboxGroupInput项目应该启用第三个selectInput。 取消选中(取消选择)第三个checkboxGroupInput项目应该禁用第三个selectInput。 同样,它的行为方式正是这样 - 如果至少选择了另一个checkboxGroupInput。 第三个selectInput将始终通过选择第三个checkboxGroupInput来启用,但取消选择第三个checkboxGroupInput项不会禁用第三个selectInput,除非当前在checkboxGroupInput中至少选择了另一个项目。

我添加了当前所选checkboxGroupInput内容的输出,以尝试了解正在发生的事情。

代码之前的最后一件事 - 我也首先使用choices而不是choiceNameschoiceValues构造checkboxGroupInput;似乎无关紧要。 此外,我第一次尝试在"if"块中进行条件测试是使用is.element而不是%in%;同样,行为没有差异。


library(shiny)
library(shinyjs)
# Let's make lists for the drop boxes
list_1 <- list("a", "b", "c")
list_2 <- list("d", "e", "f")
list_3 <- list("g", "h", "i")
list_4 <- list("j", "k", "l")
# Define UI for application 
ui <- fluidPage(
useShinyjs(),  # Set up shinyjs
# Application title
titlePanel("What's wrong with this??"),
# Sidebar
sidebarLayout(
sidebarPanel(
checkboxGroupInput("enabled", "Search Filters to Enable:",
choiceNames = list("List_1", "List_2", "List_3", "List_4"),
choiceValues = list("List_1_chosen", "List_2_chosen", "List_3_chosen", "List_4_chosen")),

# Input: Select from the following lists - default behavior is they are all disabled to start
disabled(selectInput("List_1_choice", "Choose from List 1:",
choices = list_1)),
disabled(selectInput("List_2_choice", "Choose from List 2:",
choices = list_2)),
disabled(selectInput("List_3_choice", "Choose from List 3:",
choices = list_3)),
disabled(selectInput("List_4_choice", "Choose from List 4:",
choices = list_4)),
verbatimTextOutput("text_choice")),

# Show a plot
mainPanel(
# empty
)
)
)
# Define server logic
server <- function(input, output) {
# This output is so I can see what's selected in the checkboxGroupInput    
output$text_choice <- renderPrint({
return(paste0(input$enabled))})

observeEvent(input$enabled, {
# Here's the problem (I think) -- this 'if' block is not working the way I expect
if("List_3_chosen" %in% input$enabled){
enable("List_3_choice")
}else{
disable("List_3_choice")
}
})
}
# Run the application 
shinyApp(ui = ui, server = server)

我有很多解决方法来完成这个项目,但我非常想了解我在这里做错了什么。

帮助! 感谢您的时间和关注。

如果未选择任何内容,checkboxGroupInput将返回NULL。您需要明确告诉observeEvent不要忽略它:

observeEvent(input$enabled, {
# Here's the problem (I think) -- this 'if' block is not working the way I expect
if("List_3_chosen" %in% input$enabled){
enable("List_3_choice")
}else{
disable("List_3_choice")
}
}, ignoreNULL = FALSE)

最新更新