问题描述
当我尝试绘制从输入变量获取的数据时,该输入变量根据区域的选择而变化,我得到一个错误,即我没有使用反应式表达式,但是我已经在其中添加了反应式函数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
返回一个反应对象(实际上是一个函数,因此您需要()
来访问它)。我将您的数据处理分为2个reactive
- 我不确定
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