【问题标题】:eventReactive with multiple eventExpr and output depends on which eventExpr triggered the reactive function具有多个 eventExpr 的 eventReactive 和输出取决于哪个 eventExpr 触发了响应函数
【发布时间】:2018-08-01 13:16:48
【问题描述】:

我正在开发一个闪亮的应用程序,它在 eventReactive 函数中有一个带有多个 eventExpr 触发器的反应变量。有没有办法在 eventReactive 函数中放置一个 if 来改变反应变量是什么?例如,下面的代码 sn -p 描述了我想要做什么。如果更改了 input$Client,我希望将“dat”乘以它们当前的因子,包含在 y 中。如果按下操作按钮,我希望将“dat”乘以 input$Factor。有没有办法做到这一点?

ui = fluidPage(
          selectInput(inputId = "Client", Label = "Choose Client",
                      choices = c("A", "B", "C", "D", "E")), 
          numericInput(inputId = "Factor", min = .5, max = 2, value = 1),
          actionButton(inputId = "Reprice"),
          dataTableOutput(outputId = "RepricedData")

)

server = function(input, output){
x = data.frame(rep(c("A", "B", "C", "D", "E"),20))
colnames(x) = "Client"
x$amount = runif(100, 50, 150)

y = data.frame(c("A", "B", "C", "D", "E"))
colnames(y) = "Client"
y$currentFactor = c(runif(5,.5,2))

rv = reactiveValues()

rv$repricedData = eventReactive(c(input$Client, input$Reprice), {
             dat = x$amount[which(x$Client == input$Client)]
             if(input$Client){
                dat = dat * y$currentFactor[which(y$Client == input$Client)]
                }else{
                  dat = dat * input$Factor
                }
                dat
})

output$repricedData = renderDataTable(
rv$repricedData()
  )
}

shinyApp(server = server, ui = ui)

【问题讨论】:

标签: r shiny


【解决方案1】:

您可以创建两个单独的observeEvents,分别监听两个输入之一。工作示例:

library(shiny)
ui = fluidPage(
  selectInput(inputId = "Client", label = "Choose Client",
              choices = c("A", "B", "C", "D", "E")), 
  numericInput(inputId = "Factor", label='numeric',min = .5, max = 2, value = 1),
  actionButton(inputId = "Reprice",'reprice'),
  dataTableOutput(outputId = "repricedData")
)

server = function(input, output){
  x = data.frame(rep(c("A", "B", "C", "D", "E"),20))
  colnames(x) = "Client"
  x$amount = runif(100, 50, 150)

  y = data.frame(c("A", "B", "C", "D", "E"))
  colnames(y) = "Client"
  y$currentFactor = c(runif(5,.5,2))

  rv = reactiveVal(x)

  # Observer that listens to changes in input$Reprice
  observeEvent(input$Reprice, {
    df = rv() # Read reactiveVal
    factor = input$Factor
    df$amount[df$Client==input$Client] = df$amount[df$Client==input$Client]*factor
    rv(df) # set reactiveVal to new value
  })

  # Observer that listens to changes in input$Client
  observeEvent(input$Client, {
    df = rv() # Read reactiveVal
    factor = y$currentFactor[y$Client==input$Client]
    df$amount[df$Client==input$Client] = df$amount[df$Client==input$Client]*factor
    rv(df) # set reactiveVal to new value
  })

  output$repricedData = renderDataTable(
    rv()
  )
}

shinyApp(server = server, ui = ui)

【讨论】:

  • 感谢您的工作示例,弗洛里安。这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
相关资源
最近更新 更多