Connect mutually dependent shiny input values

2019-08-01 09:58发布

I have an issue. I'd like to have an shiny app which could have two input widgets for numeric values. Let's calle them X and P. One lets user introduce a numeric figure and the other a percent variation. Both figures can be calculated using the other one.

P*C+C=X with C being for example 1000.

What I'd like to do is when user changes P then X changes and same in the other way around (user changes X and P changes) I know how to do this in one way but not in two ways. Anyone know how to solve this situation?

1条回答
Melony?
2楼-- · 2019-08-01 11:01

There are a few ways to do this, here is one way:

library(shiny)
u <- shinyUI(fluidPage(
  titlePanel("Mutually Dependent Input Values"),
  sidebarLayout(
    sidebarPanel(
      numericInput("X", "X",2000),
      numericInput("P", "P",1),
      numericInput("C", "C",1000)
    ),
    mainPanel(
      verbatimTextOutput("result")
    )
  )
)) 
s <- shinyServer(function(input, output,session) {

  observeEvent(input$P,{
    newX <- input$P*input$C + input$C
    updateNumericInput(session, "X", value = newX) 
    })
  observeEvent(input$X,{ 
    newP <- (input$X - input$C)/input$C
    updateNumericInput(session, "P", value = newP) 
    })
  output$result<-renderPrint({
    val <- input$P*input$C + input$C
    print(sprintf("X:%.0f P:%.0f C:%.0f  -   P*C + C:%.0f",input$X,input$P,input$C,val))
  })
})
shinyApp(u,s)

Yielding:

enter image description here

Not sure this is the best way, it occilates if you start out in a state that is inconsistent - need to think about how to suppress this.

查看更多
登录 后发表回答