我正在处理一个闪亮的应用程序,该应用程序在eventReactive函数中具有带有多个eventExpr触发器的反应变量。有没有办法在eventReactive函数中放置一个if来改变反应变量的含义?例如,下面的代码片段描述了我想要做的事情。如果输入$ Client被更改,我想要" dat"乘以其当前因子,包含在y中。如果按下动作按钮,我希望" dat"乘以输入$ 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)
答案 0 :(得分:0)
您可以制作两个单独的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)