R Shiny checkboxGroupInput - 单击选中所有复选框

时间:2015-03-03 10:40:15

标签: r shiny

我有一个包含checkboxGroupInput的R Shiny应用程序,我正在尝试使用updateCheckboxGroupInput函数创建一个“全选”按钮。 您可以在下面看到完整的代码,但基本上我定义了这样的cb组:

checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list)

然后,在按钮上单击,调用函数:

updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)

我有一个迹象表明函数已经运行,但它的作用实际上是取消选中复选框。 顺便说一句,当我把选择它放在定义cbGroupInput时它确实有效,但不是在函数上。

谢谢!

这是我的服务器.R:

library(shiny)
source('usefulFunctions.R')
shinyServer(function(input, output, session) {

  output$cascading <- renderUI({
    provider_id <- input$provider
    if (provider_id == "") return(NULL)
    campaigns_list <<- t(getCampaigns(provider_id))
    tagList(
      checkboxGroupInput("campaigns","Choose campaign(s):", 
                         choices = campaigns_list, selected = campaigns_list),
      actionLink("selectall","Select All")
      )
  })

  observe({
    if(is.null(input$selectall)) return(NULL)
    if (input$selectall > 0)
    {
      print(campaigns_list)
      updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
    }
    })


})

2 个答案:

答案 0 :(得分:11)

我还通过检查按钮或链接是否可被2整除来添加选择和取消选择选项

#rm(list = ls())
library(shiny)
campaigns_list <- letters[1:10]

ui =fluidPage(
  checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list),
  actionLink("selectall","Select All") 
)
server = function(input, output, session) {

  observe({
    if(input$selectall == 0) return(NULL) 
    else if (input$selectall%%2 == 0)
    {
      updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list)
    }
    else
    {
      updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
    }
  })
}
runApp(list(ui = ui, server = server))

答案 1 :(得分:2)

如果campaigns_list是一个列表,可能是因为您指定了所有选项的列表,而不是应在selected updateCheckboxGroupInput参数中选择的框的值}。

尝试将selected=campaigns_list替换为selected=unlist(campaigns_list)

以下是虚拟名称的示例:

library(shiny)
server<-function(input, output,session) {
  observe({
    if(input$selectall == 0) return(NULL)
    else if (input$selectall > 0)
    {
      variables<-list("Cylinders" = "cyl","Transmission" = "am","Gears" = "gear")
      updateCheckboxGroupInput(session,"variable","Variable:",choices=variables,selected=unlist(variables))
    }
  })
}

ui <- shinyUI(fluidPage(        
    checkboxGroupInput("variable", "Variable:",list("Cylinders" = "cyl","Transmission" = "am","Gears" = "gear")),
    actionButton("selectall", "Select All")
))
shinyApp(ui = ui, server = server)