我正在尝试在 Shinyapp 中绘图,但出现反应性错误

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

当我试图绘制从根据区域选择而变化的输入变量获得的数据时,我收到一个错误,提示我没有使用反应式表达式,但我已经添加了反应式server.R 文件中的函数。

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

})

.getReactiveEnvironment()$currentContext() 错误: 没有活动的反应上下文不允许操作。 (你试图做一些只能从反应式表达式或观察者内部完成的事情。)

这是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")
    )
)
))

反应上下文可以通过 shiny 中的几个函数创建,例如renderPlot。您不需要将所有内容都包裹起来 reactive

您的代码有几个问题:

  • 你需要一个ui
  • reactive returns 反应对象(实际上它是一个函数,因此您需要 () 才能访问它)。我将你的数据处理分为 2 reactives
  • 我不确定 quoted = TRUE 属于哪个函数,我假设 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)

如果你想阅读更多关于shiny的内容,我推荐你这个book