checkboxGroupInput - 设置最小和最大选择数 - 刻度

checkboxGroupInput - set minimum and maximum number of selections - ticks

这是带有复选框组输入的示例代码:

library(shiny)

server <- function(input, output) {
  output$Selected <- renderText({
    paste(input$SelecetedVars,collapse=",")
  })
}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("SelecetedVars", "MyList:",
                         paste0("a",1:5), selected = "a1")
    ),
    mainPanel(textOutput("Selected"))
  )
)

shinyApp(ui = ui, server = server)

正如您从上图中看到的那样,我们可以 select 任意数量,在本例中为 5 中的 4。

如何设置最小和最大刻度数?我至少需要检查 1 个选项,最多检查 3 个选项。即:防止 取消勾选 最后一个勾选,并防止在 3 个选项已经 勾选 时勾选。

你可以这样做:

library(shiny)

my_min <- 1
my_max <- 3

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("SelecetedVars", "MyList:",paste0("a",1:5), selected = "a1")
    ),
    mainPanel(textOutput("Selected"))
  )
)

server <- function(input,output,session) {

  output$Selected <- renderText({
    paste(input$SelecetedVars,collapse=",")
  })

  observe({
    if(length(input$SelecetedVars) > my_max){
      updateCheckboxGroupInput(session, "SelecetedVars", selected= tail(input$SelecetedVars,my_max))
    }
    if(length(input$SelecetedVars) < my_min){
      updateCheckboxGroupInput(session, "SelecetedVars", selected= "a1")
    }
  })
}

shinyApp(ui = ui, server = server)

你可以用一点JavaScript来做:

## In a file named 'js4checkbox.js' in your app folder :
$(document).ready(function(){
  $('input[name=SelecetedVars]').on('click', function(event){
    if($('input[name=SelecetedVars]:checked').length > 3){
      $(this).prop('checked', false);
    }
  });
  $('input[name=SelecetedVars]').on('click', function(event){
    if($('input[name=SelecetedVars]:checked').length == 0){
      $(this).prop('checked', true);
    }
  });
});

并在您的 ui 中添加:

fluidPage(
  includeScript(path = "js4checkbox.js"),
  ...
)

我不知道为什么,但它在 RStudio 查看器中效果不佳,因此请在浏览器中打开它。

对于 JavaScript 代码,请参阅此 post