如何在Shiny中实现自定义默认值的ActionButton功能
解决方案
要实现“Customized”按钮的自定义设置功能,我们可以结合Shiny的输入更新函数,直接修改对应控件的值。以下是修改后的完整代码:
library(shiny) library(shinyjs) library(ggplot2) # 原代码使用了ggplot但未加载该包,需补充 shinyApp( ui <- fluidPage( sidebarPanel( fluidRow( shinyjs::useShinyjs(), id = "panel_vars", # Buttons uiOutput("varx"), uiOutput("vary"), numericInput("ptSize", "Point size", min=.1, max=5, value = 2), actionButton("p1", 'Reset variables XY'), helpText(""), actionButton("p2", 'Customized') ) ), mainPanel( plotOutput("plot") ) ), server <- function(input, output, session) { # 添加session参数用于更新输入 getModel <- reactive({ names(mtcars) }) output$varx <- renderUI({ selectInput("varsel.x", "Select var X", choices = as.list(getModel()), multiple = F) }) output$vary <- renderUI({ selectInput("varsel.y", "Select var Y", choices = as.list(getModel()), multiple = F) }) observeEvent(input$p1, { shinyjs::reset("panel_vars") }) # 新增Customized按钮的触发逻辑 observeEvent(input$p2, { updateSelectInput(session, "varsel.x", selected = "disp") updateSelectInput(session, "varsel.y", selected = "drat") updateNumericInput(session, "ptSize", value = 1.0) }) output$plot <- renderPlot({ p <- mtcars %>% ggplot(aes_string(x=input$varsel.x, y=input$varsel.y))+ geom_point(size=input$ptSize) p }) } )
关键修改说明:
- 补充加载
ggplot2包,避免代码运行时出现函数未找到的错误 - 在server函数中添加
session参数,这是使用update*Input系列函数的必要条件 - 通过
observeEvent监听“Customized”按钮的点击事件,分别用updateSelectInput和updateNumericInput设置指定的自定义值
内容的提问来源于stack exchange,提问作者Hassan Camil David
相关产品推荐
相关产品推荐

