闪亮 - 如何有条件地更新被动或被动价值?

时间:2016-01-26 15:09:56

标签: r if-statement shiny

我试图用一些ifelse条件更新值。

例如,在下面的代码中,我只想更新被动"乘数"如果反应性" decim_factor"改变它的价值,而不是它只是更新。我尝试将observeEvent用于" decim_factor"作为eventExpr,但它没有工作。

library(shiny)
rm(list = ls())

ui <- shinyUI(pageWithSidebar(
  headerPanel("Click the button"),
  sidebarPanel(
    numericInput("index","Numeric Input",1),

    p("This is the criteria to change the decim_factor depending on numericInput"),
    br(),
    p(" num_input >= 20 - decim_factor=3"),
    p("20  > num_input >= 10 - decim_factor=2"),
    p("10  > num_input       - decim_factor=1")

  ),
  mainPanel(
    verbatimTextOutput("decim"),
    verbatimTextOutput("multip")
  )
))


server <- shinyServer(function(input, output) {

  decim_factor <- reactive({
    num_input <- input$index
    if(num_input>=20)                      {decim_factor <- 3} 
    else if(10<=num_input & num_input<20)  {decim_factor <- 2}
    else                                    decim_factor <- 1
    as.numeric(decim_factor)
  })
  #I was trying to calculte the 'multiplier' only if 'decim_factor' changes its value
  #and not if it is updated
  #
  #I tried to use observeEvent, depending on decim_factor() but it didn't work
  #If I put the observeEvent function as comment it works, but the multiplier
  #updates every time I change the numeric_input
  observeEvent(decim_factor(),{
    multiplier <- reactive({
      decim_factor()*10
    })
  })

  #The outputs come with da Sis.time() just to check if the values are updated
  output$decim <- renderText({paste("Decim = ",decim_factor(), ";",Sys.time())})
  output$multip <- renderText({paste("Muliplier =", multiplier(), ";",Sys.time())})
}) 

shinyApp(ui,server)

1 个答案:

答案 0 :(得分:1)

即使decim_factor的值没有变化,您也会在被动中重置它,因此会触发更新multiplier的observeEvent。如果你想阻止这种情况,你可以这样做:

server <- shinyServer(function(input, output) {
        values <- reactiveValues(decim_factor=1,multiplier=10)

        observeEvent(input$index,{
                num_input <- input$index
                if(num_input>=20 & values$decim_factor != 3) {values$decim_factor <- 3} 
                else if(10<=num_input & num_input<20 & values$decim_factor != 2 )  {values$decim_factor <- 2}
                else if(10>num_input & values$decim_factor != 1) values$decim_factor <- 1
        })

        observeEvent(values$decim_factor,{
                values$multiplier <- values$decim_factor*10
        })

        output$decim <- renderText({paste("Decim = ",values$decim_factor, ";",Sys.time())})
        output$multip <- renderText({paste("Muliplier =", values$multiplier, ";",Sys.time())})
})

当需要更改值时,第一个if/else中的observeEvent仅更新values$decim_factor