如何使用 actionButton 更改 R Shiny 中 selectInput 上的选定值?
Posted
技术标签:
【中文标题】如何使用 actionButton 更改 R Shiny 中 selectInput 上的选定值?【英文标题】:How to use an actionButton to change the selected value on a selectInput in R Shiny? 【发布时间】:2021-10-05 13:10:37 【问题描述】:我正在使用具有项目列表的选择输入构建一个闪亮的应用程序。默认情况下,选择数据中的所有项目。我想要 2 个操作按钮来帮助用户。一个重置为默认值并已全部选中(我已经弄清楚了),另一个删除所有并将 selectInput 更改为“请至少选择一个项目”(这实际上与删除所有选项相同,因为没有具有该名称的项目)。这第二个按钮我想不通。
我的代码如下,非常感谢任何帮助:
library(shiny)
library(shinyjs)
test <- tibble(project = c("Justin", "Corey","Sibley"),
april_2021 = c(10, 100, 101),
may_2021 = c(1, 4, 7))
ui <- fluidPage(
useShinyjs(),
sidebarLayout(
sidebarPanel(
div(id = "project_inputs",
selectInput(inputId = "filter_by_project",
label = "Filter by Project",
choices = c(sort(unique(test$project)), "Please Select at Least One Project"),
multiple = TRUE,
selected = sort(unique(test$project)))),
#I can't figure out the remove_all button
actionButton(inputId = "remove_all",
label = "Unselect All Projects", style = "color: #FFFFFF; background-color: #CA001B; border_color: #CA001B"),
actionButton(inputId = "add_all",
label = "Select All Projects", style = "color: #FFFFFF; background-color: #CA001B; border_color: #CA001B"),
),
mainPanel(
)
)
)
server <- function(input, output)
#This is where the remove_all will go
observeEvent(input$remove_all,
reset("add_all")
)
shinyApp(ui = ui, server = server)
【问题讨论】:
【参考方案1】:试试这个
library(shiny)
library(shinyjs)
test <- tibble(project = c("Justin", "Corey","Sibley"),
april_2021 = c(10, 100, 101),
may_2021 = c(1, 4, 7))
ui <- fluidPage(
useShinyjs(),
sidebarLayout(
sidebarPanel(
div(id = "project_inputs",
selectizeInput(inputId = "filter_by_project",
label = "Filter by Project",
choices = sort(unique(test$project)),
multiple = TRUE,
selected = unique(test$project)[1] )),
#I can't figure out the remove_all button
actionButton(inputId = "remove_all",
label = "Unselect All Projects", style = "color: #FFFFFF; background-color: #CA001B; border_color: #CA001B"),
actionButton(inputId = "add_all",
label = "Select All Projects", style = "color: #FFFFFF; background-color: #CA001B; border_color: #CA001B"),
),
mainPanel(
)
)
)
server <- function(input, output, session)
observeEvent(input$remove_all,
updateSelectizeInput(session,"filter_by_project",choices=sort(unique(test$project)),
selected=NULL, options = list(placeholder="Please Select at Least One Project")
)
)
observeEvent(input$add_all,
updateSelectizeInput(session,"filter_by_project",choices=sort(unique(test$project)), selected=sort(unique(test$project)) )
)
shinyApp(ui = ui, server = server)
【讨论】:
以上是关于如何使用 actionButton 更改 R Shiny 中 selectInput 上的选定值?的主要内容,如果未能解决你的问题,请参考以下文章
在 R 闪亮的模块中使用 actionButton + insertUI 创建多个输入
在 R Shiny 中使用 ActionButton 跳转到选项卡项
R Shiny:在服务器端使用 Actionbutton 的 Onclick 选项