Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive variables in Shiny for later calculations

Tags:

r

shiny

Total novice here.

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

output$text_calc <- renderText({
    paste("The result is =", input$num_W * input$num_l - input$slider_a... )
    })

To avoid my brain exploding with long formulas, how can I define the inputs as single letter variables? I've tried l <- input$num_l which gives me

"Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)"

Putting reactive({}) around the code gives

Error: cannot coerce type 'closure' to vector of type 'character'

like image 850
komodovaran_ Avatar asked Jan 22 '26 14:01

komodovaran_


1 Answers

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)

enter image description here

like image 92
Pork Chop Avatar answered Jan 25 '26 07:01

Pork Chop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!