SAIF UL MEHDI
SAIF UL MEHDI

Reputation: 27

I am trying to plot in Shinyapp but I am getting a reactive error

When I am trying to plot a data which is obtained from an input variable which changes according to choice of the region, I am getting an error that is saying I am not using reactive expression but I have already added the reactive function in the server.R file.

library(shiny)
library(forecast)
shinyServer(function(input, output) {

reactive(if(input$Region == 'India')
            df<-read.csv('COVID.csv',row.names=1)
        else if(input$Region == 'Telangana')
            df<-read.csv('ts_covid.csv',row.names=1)
        else
            df<-read.csv('ghmc_covid.csv',row.names=1),
        quoted=TRUE)
        mdl<-auto.arima(df$DailyCases)
        future<-forecast(mdl,h=input$Days,level=95)
        output$Plot1<-renderPlot({
        plot(future)
    })

})

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

Here is the ui.R

library(shiny)
shinyUI(fluidPage(
titlePanel("Forecast of COVID Cases"),
sidebarLayout(
    sidebarPanel(
        h3('Select the Region where you want the forecast'),
        selectInput("Region","Region to be selected",choices=
                        list('India','Telangana','GHMC')),
        h3('Select for how many days you want the forecast for'),
        numericInput('Days','Number of Days',value=7,min=1,max=30,step=1)
    ),

    mainPanel(
        plotOutput("Plot1")
    )
)
))

Upvotes: 0

Views: 67

Answers (1)

starja
starja

Reputation: 10375

A reactive context can be created by several functions in shiny, e.g. renderPlot. You don't need to wrap reactive around everything.

Your code has a few issues:

  • you need a ui
  • reactive returns a reactive object (actually it's a function, therefore you need () to access it). I split up your data processing into 2 reactives
  • I'm not sure to which function quoted = TRUE belongs, I assume read.csv
library(shiny)
library(forecast)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "Region",
                  label = "Region",
                  choices = c("India", "Telagana", "GHMC"))
    ),
    
    mainPanel(
      plotOutput("Plot1")
    )
  )
)

server <- function(input, output, session) {
  df <- reactive({
    if(input$Region == 'India')
      df<-read.csv('COVID.csv',row.names=1)
    else if(input$Region == 'Telangana')
      df<-read.csv('ts_covid.csv',row.names=1)
    else
      df<-read.csv('ghmc_covid.csv',row.names=1, quoted=TRUE)
    df
    
  })
  future <- reactive({
    
    mdl<-auto.arima(df()$DailyCases)
    future<-forecast(mdl,h=input$Days,level=95)
    future
  })
  
  output$Plot1<-renderPlot({
    plot(future())
  })
}

shinyApp(ui, server)

If you want to read more about shiny, I recommend you this book

Upvotes: 1

Related Questions