1

我是 R 开发的新手,我正在努力实现这一目标。我有一段代码,我观察到两个操作按钮等待点击它们。现在我想在 if 语句中知道点击了其中一个,但我的实现不起作用。我已经搜索了一些可能的解决方案,但我找不到它。有人可以给我一点帮助吗?谢谢!

observeEvent({c(input[["button1"]], input[["button2"]])}, {        

      output$mean<- renderPlotly({            

       if(input[["button1"]]){ 

           output_mean(out(), start_date(), geo(), language(), grupo(), TRUE, "button1")

        }else if(input[["button2"]]){

           output_mean(out(), start_date(), geo(), language(), grupo(), TRUE, "button2")

        }
      })

    #}
  })
4

1 回答 1

2

两件事情:

  • render*函数本质上是反应式的,因此它们不应该嵌套在另一个函数中。在这种情况下,它已经能够在不添加任何内容的情况下做出反应。

  • 操作按钮每次按下时都会增加其值。这意味着如果用户点击它的速度快于 R 的反应速度,它实际上可能会增加 2(不太可能但可能可行)。按钮的值更改(递增)的行为是触发反应的原因,因此您需要知道之前的值是什么才能知道单击了哪个(假设只有一个)。

尝试以下操作:

server <- function(input, output, session) {
  buttonstates <- reactiveValues(one=0, two=0)
  output$mean <- renderPlotly({
    req(input$button1, input$button2)
    if (input$button1 != buttonstates$one) {
      buttonstates$one <- input$button1
      output_mean(out(), start_date(), geo(), language(), grupo(), TRUE, "button1")
    } else if (input$button2 != buttonstates$two) {
      buttonstates$two <- input$button2
      output_mean(out(), start_date(), geo(), language(), grupo(), TRUE, "button2")
    }
  })
}

另一种选择是将按钮确定分离到它自己的反应块中。这样做的好处是它简化了你的renderPlotly块:

server <- function(input, output, session) {
  buttonstates <- reactiveValues(one=0) # don't need two=0
  whichbutton <- reactive({
    req(input$button1, input$button2)
    if (input$button1 != buttonstates$one) "button1" else "button2"
  })
  output$mean <- renderPlotly({
    req(whichbutton())
    output_mean(out(), start_date(), geo(), language(), grupo(), TRUE, whichbutton())
  })
}

(如果您不熟悉,如果uired 变量不是“真实的”,如 所定义shiny::req,它会阻止块触发。这是防止在闪亮启动和/或其他问题期间过早触发的便捷方法。)reqshiny::isTruthy

于 2018-04-15T19:51:13.150 回答