Ciaran O Brien
Ciaran O Brien

Reputation: 384

renderText in RShiny with conditions If Else

I am in my server.r file and trying to create an output via renderText with a conditional statement. The below code is throwing me the error:

Error in .getReactiveEnvironment()$currentContext() : 
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.)```

I have a feeling I have the architecture of this code wrong.

if (A > B)
  {
    output$sample <- renderText({ do some calculation)})
  }
else if(A <= B)
  {
    output$sample <- renderText({do some other calculation)})
  }

I have attempted to reformat to the below but get the same error. I feel I may be fundamentally wrong in my approach here. Any help welcomed.

output$sample <-
    if (A > B)
      {
         renderText({ do some calculation)})
      }
    else if(A <= B)
      {
        renderText({do some other calculation)})
      }

Upvotes: 0

Views: 164

Answers (1)

YBS
YBS

Reputation: 21349

Server part where the issue was has been resolved here with some reactive objects. Please try this

ab <- reactive({req(input$account_value) - req(input$blocked_funds)})
  
  # free funds
  output$free_funds <- renderText({ab()})
  
  # current margin
  cm <- reactive({
    req(input$account_value,input$blocked_funds)
    if (input$account_value > input$blocked_funds){
      curmargin <- round(input$account_value/(input$account_value+input$blocked_funds), digits = 2)
    }else { 
      curmargin <- round((.5*(input$account_value))/input$blocked_funds, digits = 2)
    }
  })
  
  
  output$current_margin <- renderText({cm()})
  
  rm <- reactive({
    req(input$account_value,input$blocked_funds)
    round(input$account_value/(input$account_value + input$blocked_funds*2.5)*100,digits = 1)
  })
  
  # New margin
  output$revised_margin <- renderText({
    paste(rm(),"%",sep = "")
  })

Upvotes: 1

Related Questions