【问题标题】:Call eventReactive for an arbitrary number of action buttons为任意数量的操作按钮调用 eventReactive
【发布时间】:2015-09-20 14:57:09
【问题描述】:

我要做的是创建任意数量的操作按钮,每个按钮都有基于它们自己的值的自己的事件。

假设我们要创建多个按钮。我们所做的是在 1 到 100 之间抽取一个随机数,并将其命名为 n。然后我们创建 n 按钮,每个按钮都有一个介于 1n 之间的值(覆盖每个数字一次)。然后,当我们按下其中一个按钮时,我们会呈现一条文本消息,即我们按下的数字。

要设置按钮,我们有:

ui.R

shinyUI(fluidPage(
   actionButton('roll','roll'),
   uiOutput('buttons')
))

Server.R

shinyServer(function(input, output) {

  n <- eventReactive(input$roll, {
    num <- sample(1:100,1)
    sample(1:num, num, replace=FALSE)
  })

  output$buttons <- renderUI({
    lapply(1:length(n()), function(i) {
      actionButton(as.character(n()[i]), as.character(n()[i]) )
    })
  })

})

这会生成按钮。但是,我正在努力寻找一种方法来创建所有必要的eventReactive()s。我尝试在循环中调用eventReactive(),并在lapply 调用中调用。但是,为了创建那个循环或lapply,您需要length(n()) 的值,它只能在另一个反应或观察命令中调用。

给定上面脚本生成的按钮,我们如何为每个按钮做一个响应式表达式,然后输出对应按下的数字的文本?

【问题讨论】:

    标签: r rstudio shiny-server shiny


    【解决方案1】:

    您可以在输入中搜索已触发的按钮。单击按钮后,其值大于 0,因此所有选择的值都会以这种方式打印(不确定是否需要?)

    library(shiny)
    
    shinyApp(
        shinyUI(fluidPage(
            sidebarLayout(
                sidebarPanel(
                    actionButton('roll','roll'),
                    uiOutput('buttons')
                ),
                mainPanel(
                    textOutput('stuff')
                )
            )
        )),
        shinyServer(function(input, output) {
    
            n <- eventReactive(input$roll, {
                num <- sample(1:100,1)
                sample(1:num, num, replace=FALSE)
            })
    
            output$buttons <- renderUI({
                lapply(1:length(n()), function(i) {
                    actionButton(as.character(n()[i]), as.character(n()[i]) )
                })
            })
    
            output$stuff <- renderText({
                val <- which(lapply(paste(n()), function(i) input[[i]]) == TRUE)
                if (length(val))
                    sprintf("Picked %s!", paste(n())[val])
            })
    
        })
    )
    

    【讨论】:

    • 谢谢,但我希望它是一个反应事件。即每次按下按钮时发生的事件。我认为,在您的示例中,该事件只能发生一次。在我正在使用的实际情况中,我希望事件正在更改另一个小部件的输入(在 observeEvent 中使用 updateSelectInput)。
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多