这是我设置全选/取消全选按钮的方法。
在ui.R中添加一个必要的操作按钮:
actionButton("selectall", label="Select/Deselect all")
然后server.R会根据操作按钮的条件使用updateCheckboxGroupInput。 如果按钮按下的次数是偶数,它将选择全部;否则,如果是奇数,则不选。
observe({
if (input$selectall > 0) {
if (input$selectall %% 2 == 0){
updateCheckboxGroupInput(session=session,
inputId="show_vars",
choices = list("carat" = "carat",
"cut" = "cut",
"color" = "color",
"clarity"= "clarity",
"depth" = "depth",
"table" = "table",
"price" = "price",
"x" = "x",
"y" = "y",
"z" = "z"),
selected = c(names(hw)))
} else {
updateCheckboxGroupInput(session=session,
inputId="show_vars",
choices = list("carat" = "carat",
"cut" = "cut",
"color" = "color",
"clarity"= "clarity",
"depth" = "depth",
"table" = "table",
"price" = "price",
"x" = "x",
"y" = "y",
"z" = "z"),
selected = c())
}}
})
以下是您所示例的完整应用程序 - 您需要将会话添加到服务器函数中,我添加了一个条件,用于在未选择变量时呈现renderDataTable。
library(shiny)
library(ggplot2)
data(diamonds)
hw <- diamonds
runApp(
list(
ui=(
fluidPage(
title = 'Examples of DataTables',
sidebarLayout(
sidebarPanel(
actionButton("selectall", label="Select/Deselect all"),
checkboxGroupInput('show_vars', 'Columns in diamonds to show:',
names(hw), selected = names(hw))
),
mainPanel(
verbatimTextOutput("summary"),
tabsetPanel(
id = 'dataset',
tabPanel('hw', dataTableOutput('mytable1'))
))))),
server = (function(input, output, session) {
output$summary <- renderPrint({
dataset <- hw[, input$show_vars, drop = FALSE]
summary(dataset)
})
observe({
if (input$selectall > 0) {
if (input$selectall %% 2 == 0){
updateCheckboxGroupInput(session=session, inputId="show_vars",
choices = list("carat" = "carat",
"cut" = "cut",
"color" = "color",
"clarity"= "clarity",
"depth" = "depth",
"table" = "table",
"price" = "price",
"x" = "x",
"y" = "y",
"z" = "z"),
selected = c(names(hw)))
}
else {
updateCheckboxGroupInput(session=session, inputId="show_vars",
choices = list("carat" = "carat",
"cut" = "cut",
"color" = "color",
"clarity"= "clarity",
"depth" = "depth",
"table" = "table",
"price" = "price",
"x" = "x",
"y" = "y",
"z" = "z"),
selected = c())
}}
})
output$mytable1 <- renderDataTable({
if (is.null(input$show_vars)){
data.frame("no variables selected" = c("no variables selected"))
} else{
hw[, input$show_vars, drop = FALSE]
}
})
})
))
server.R
,ui.R
以及测试程序所需的任何数据。 - nrussellselectize(multiple = TRUE)
而不是checkboxGroupInput()
?您还将selected =
设置为names(...)
,这就是为什么所有内容都被选中的原因 - 只需将selected = ''
修复即可。此解决方案无法获得“全部”选项(即使我也在寻找),但对于 ~10 个选择,我认为这是正确的方法。可能是错误的。 - d8aninja