【问题标题】:I am trying to plot in Shinyapp but I am getting a reactive error我正在尝试在 Shinyapp 中进行绘图,但出现反应性错误
【发布时间】:2020-12-21 06:39:26
【问题描述】:

当我试图绘制从输入变量中获得的数据时,该输入变量会根据区域的选择而变化,我收到一个错误,说我没有使用反应式表达式,但我已经在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")
    )
)
))

【问题讨论】:

    标签: r shiny reactive-programming shinyapps


    【解决方案1】:

    可以通过shiny 中的多个函数创建反应式上下文,例如renderPlot。您无需将reactive 包裹在所有内容中。

    您的代码有一些问题:

    • 你需要一个ui
    • reactive 返回一个响应式对象(实际上它是一个函数,因此您需要 () 才能访问它)。我将您的数据处理分成 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

    【讨论】:

    • 我已按要求添加了 ui.R
    • 谢谢!抱歉,在我的回答中我犯了复制/粘贴错误,现在您应该看到我的解决方案
    • 我相信引用不是必需的。现在它运行良好,但情节没有被渲染
    • 感谢您的评论,错误是我使用plot(future)而不是plot(future())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2022-01-23
    • 2023-02-14
    相关资源
    最近更新 更多