问题
I'm working on a shiny application that has a reactive variable with multiple eventExpr triggers in an eventReactive function. Is there a way to place an if within the eventReactive function to change what the reactive variable will be? For example, the code snippet below describes what I want to do. If input$Client is changed, I want the "dat" to be multiplied by their current factor, contained in y. If the action button is hit, I would like the "dat" to be multiplied by input$Factor. Is there a way to accomplish this?
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)
回答1:
You could make two separate observeEvents that listen to one of both inputs. Working example:
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)
来源:https://stackoverflow.com/questions/48914706/eventreactive-with-multiple-eventexpr-and-output-depends-on-which-eventexpr-trig