Ошибка RShiny: ошибка в .getReactiveEnvironment() $ CurrentContext()

#r #shiny

#r #блестящий

Вопрос:

Я получаю следующую ошибку:

  "The following error happened while the function call GetForwardProduct():n 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.)n"
  

Мой пользовательский интерфейс выглядит так:

 shinyUI(fluidPage(

                 dateRangeInput(inputId = "maSpreadDateRange", label = "Select Date Range", 
                                start = "2016-01-01", end = Sys.Date()),
                 selectInput(inputId = "maCommodity2", label = "Select Commodity", 
                             choices = c("Power", "Gas", "Oil", "Coal", "CO2", "EUR/USD")),
                 uiOutput(outputId = "maOutputMarketArea2"),
                 uiOutput(outputId = "maOutputBasePeak2"),
                 textInput(inputId = "maProd2", label = "Define Forward Product", value = "Cal-2021"),
                 actionButton(inputId = "goSpread", label = "Calculate")
                 
))
  

Мой сервер:

 shinyServer(
function(input, output) {

  # Dynamical input selection for market area 2: #
  output$maOutputMarketArea2 <- renderUI({
    
    try({
      
      commodity <- input$maCommodity2
      
      if (commodity == "Power"){
          selectInput(inputId = "maMarketArea2", label = "Select Market Area", choices = c("DE", "AT"))
      } else if (commodity == "Gas"){
          selectInput(inputId = "maMarketArea2", label = "Select Market Area", choices = c("TTF", "NCG", "CEGH VTP"))
      } 
      
    })
    
  })
  
  # Dynamical input selection for base or peak 1: #
  output$maOutputBasePeak2 <- renderUI({
    
    try({
      
      commodity <- input$maCommodity2
      
      if (commodity == "Power"){
          selectInput(inputId = "maBasePeak2", label = "Select Base or Peak", choices = c("Base", "Peak"))
      }
      
    })
    
  })
  
  # Reactive expression for product 2 function call: #
  comm <- input$maCommodity2
  marketA <- input$maMarketArea2
  baseP <- input$maBasePeak2

      maProduct2 <- reactive({
        maProduct2 <- GetForwardProduct(commodity = comm, marketArea = marketA, basePeak = baseP, 
                                        product = input$maProd2)
      })
      

 
  

Я не знаю, как использовать реактивное выражение, я очень новичок в RShiny! Функция GetForwardProduct() в reactive({ }) — это функция, которая объединяет строки вместе.
Функция MASpread() работает нормально, но не с реактивным выражением. Кто-нибудь может мне помочь??

Комментарии:

1. Не создавайте переменные comm marketA и baseP вне вашего реактивного, а просто используйте input$maCommodity2 и так далее в реактивном непосредственно в GetForwardProduct вызове. input Переменные являются реактивными значениями, которые вы вызываете в server , которая не является реактивной средой

2. @starja спасибо, теперь ошибка с реактивным значением больше не отображается! Но есть так много других ошибок и предупреждений…..

3. Попробуйте разобраться в сообщениях об ошибках и погуглите их; Я также рекомендую прочитать блестящий учебник

4. Проблема в том, что print(maProduct2) это ничего не дает. Значит, что-то не работает с reactive({}) частью.

Ответ №1:

Вы должны помнить, что ввод должен быть заключен в reactive, а reactive должен быть связан с () . Например, я немного переписываю ваш код в форме, чтобы он работал, и печатает текст с вводом, который выбирает пользователь. Я завернул maProduct2 в реактивный и распечатал этот реактивный, используя renderText и verbatimTextOutput, как видно ниже. Я не знаю, что делает ваша функция getForwardProduct(), поэтому я просто использовал paste() для иллюстрации ниже.

 

library(shiny)

ui <- fluidPage(
  dateRangeInput(
    inputId = "maSpreadDateRange",
    label = "Select Date Range",
    start = "2016-01-01",
    end = Sys.Date()
  ),
  selectInput(
    inputId = "maCommodity2",
    label = "Select Commodity",
    choices = c("Power", "Gas", "Oil", "Coal", "CO2", "EUR/USD")
  ),
  uiOutput(outputId = "maOutputMarketArea2"),
  uiOutput(outputId = "maOutputBasePeak2"),
  textInput(
    inputId = "maProd2",
    label = "Define Forward Product",
    value = "Cal-2021"
  ),
  actionButton(inputId = "goSpread", label = "Calculate"),
  

  verbatimTextOutput("text")
)


server <- function(input, output, session) {
  # Dynamical input selection for market area 2: #
  output$maOutputMarketArea2 <- renderUI({
    try({
      commodity <- input$maCommodity2
      
      if (commodity == "Power") {
        selectInput(
          inputId = "maMarketArea2",
          label = "Select Market Area",
          choices = c("DE", "AT")
        )
      } else if (commodity == "Gas") {
        selectInput(
          inputId = "maMarketArea2",
          label = "Select Market Area",
          choices = c("TTF", "NCG", "CEGH VTP")
        )
      }
      
    })
    
  })
  
  # Dynamical input selection for base or peak 1: #
  output$maOutputBasePeak2 <- renderUI({
    try({
      commodity <- input$maCommodity2
      
      if (commodity == "Power") {
        selectInput(
          inputId = "maBasePeak2",
          label = "Select Base or Peak",
          choices = c("Base", "Peak")
        )
      }
      
    })
    
  })
  

  maProduct2 <- reactive({
    paste(input$maCommodity2,
          input$maBasePeak2,
          input$maProd2)
  })
  
  output$text <- renderText({
    maProduct2()
  })
  
  
}

shinyApp(ui, server)