Reactive variables in Shiny for later calculations

前端 未结 2 2001
無奈伤痛
無奈伤痛 2021-01-15 02:15

Total novice here.

I have an output that writes the result of a formula, with variables based on inputs

output$text_calc <- renderText({
    paste         


        
相关标签:
2条回答
  • 2021-01-15 02:59

    If you want to reuse this formula elsewhere, to avoid recalculating it :

    server <- shinyServer(function(input, output,session){
    
      formula <- reactive({
        W <- input$num_W
        L <- input$num_l
        A <- input$slider_a
        W*L-A
      })
    
    
      output$text_calc <- renderText({
        paste("The result is =", formula())
      })
    
    
    })
    
    0 讨论(0)
  • 2021-01-15 03:16

    Try something like the example below. Also, note to use the inputs within the reactive expressions

    Example 1

    #rm(list = ls())
    library(shiny)
    ui <- shinyUI(fluidPage(
      mainPanel(
        numericInput("num_W", "Observations:", 10,min = 1, max = 100),
        numericInput("num_l", "Observations:", 10,min = 1, max = 100),
        sliderInput("slider_a","test",value = 1,min=1,max=20,step=1),
        textOutput("text_calc"))
    ))
    server <- shinyServer(function(input, output,session){
      output$text_calc <- renderText({
        W <- input$num_W
        L <- input$num_l
        A <- input$slider_a
        paste("The result is =", W*L-A)
      })
    })
    
    shinyApp(ui = ui, server = server)
    

    Example 2, using reactiveValues()

    #rm(list = ls())
    library(shiny)
    ui <- shinyUI(fluidPage(
      mainPanel(
        numericInput("num_W", "Observations:", 10,min = 1, max = 100),
        numericInput("num_l", "Observations:", 10,min = 1, max = 100),
        sliderInput("slider_a","test",value = 1,min=1,max=20,step=1),
        textOutput("text_calc"))
    ))
    server <- shinyServer(function(input, output,session){
      
      vals <- reactiveValues()
      observe({
        vals$W <- input$num_W
        vals$L <- input$num_l
        vals$A <- input$slider_a
      })
      
      output$text_calc <- renderText({
        paste("The result is =", vals$W*vals$L-vals$A)
      })
    })
    
    shinyApp(ui = ui, server = server)
    

    0 讨论(0)
提交回复
热议问题