【问题标题】:How to use selectInput like an actionButton?如何像 actionButton 一样使用 selectInput?
【发布时间】:2021-09-09 19:43:42
【问题描述】:

我正在尝试将 selectInput 用作操作按钮。我喜欢每次按下 actionButton 时,计数器都会添加数字。我正在尝试为 selectInput 实现相同的效果。

在下面的示例中,我演示了 actionButton 的功能。我试图用这个代码来模仿它的效果。

 selectnumber <- eventReactive(input$select,
                                if (input$select == "A") {
                                             input$action + 1
  })
  

在这种方法中,数字会更新,但这取决于 actionButton。相反,我希望在选择 B 后选择 A 时更新数字。

library(shiny)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
          selectInput("select", "Select Input", choices = c(" ", "A", "B")),
          actionButton("action", "Action Button")
        ),
        mainPanel(
         textOutput("out1"),
          textOutput("out2")
        )
    )
)

server <- function(input, output) {
  output$out1 <- renderText({
    paste("Action Button: ", input$action)
  })
  
#  count <- reactive({
#    input$action
# })
  
  selectnumber <- eventReactive(input$select,
                                if (input$select == "A") {
   input$action + 1
  })
  
  output$out2 <- renderText({
    paste("Select Input: ", selectnumber())
  })
}

options(shiny.autoreload = TRUE)
shinyApp(ui = ui, server = server)


有没有更好的工作方式让 selectInput 表现得像 actionButton?

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    这是使用observeEventreactiveValues 的一种方法。每次您在 selectInput 中选择 'A' 时,计数都会增加。

    library(shiny)
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          selectInput("select", "Select Input", choices = c(" ", "A", "B")),
          actionButton("action", "Action Button")
        ),
        mainPanel(
          textOutput("out1"),
          textOutput("out2")
        )
      )
    )
    
    server <- function(input, output) {
    
      rv <- reactiveValues(count = 0)
      output$out1 <- renderText({
        paste("Action Button: ", input$action)
      })
      
      observeEvent(input$select, {
              if (input$select == "A") rv$count <- rv$count + 1
      })
      
      output$out2 <- renderText({
        paste("Select Input: ", rv$count)
      })
    }
    
    options(shiny.autoreload = TRUE)
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 2021-10-05
      • 2019-07-13
      • 1970-01-01
      • 2019-02-23
      • 2016-02-03
      • 2023-03-28
      • 2015-04-15
      相关资源
      最近更新 更多