首页 > 解决方案 > 带有条件的 RShiny 中的 renderText If Else

问题描述

我在我的 server.r 文件中,并尝试通过带有条件语句的 renderText 创建输出。下面的代码向我抛出了错误:

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.)```

我有一种感觉,我有这个代码的架构错误。

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

我试图重新格式化为以下但得到同样的错误。我觉得我在这里的方法可能从根本上是错误的。欢迎任何帮助。

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

标签: rshiny

解决方案


问题所在的服务器部分已在此处通过一些反应对象解决。请试试这个

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 = "")
  })

推荐阅读