具有外生变量的 VAR 模型在 Shiny 中不起作用

VAR model with exogenous variable doesn't work in Shiny

让我们考虑一个带有外生变量的 VAR 模型来区分两个时期。该模型完美运行如下:

library(shiny)
library(vars)

#--- Create Exogenous Variable 'periods'
data(Canada)
canTS <- Canada
periods <- as.matrix(data.frame(period=ifelse(index(canTS)>1996, 1, 0 ) ) )

#--- Fit the Model
fit1 <- VAR(Canada, p = 2, type = "none", exogen=periods)
coef(fit1)[[1]]

#-- Make Prediction
period2 <- as.matrix(data.frame(period = rep(1, 12)) ) # Future Exogen Values = 1 
predict(fit1, n.ahead=12, dumvar=period2)

rm(list=ls(all=TRUE)) # remove objects

使用带有滑块输入(指定预测范围)的 Shiny 应用程序时出现问题。我们可以创建一个简单的 Shiny 应用程序:

ui <- fluidPage(
 sidebarLayout(
  sidebarPanel(
   sliderInput(inputId = "nAhead",
    label = "Forecast Period",
    min = 1,
    max = 12,
    value = 6)
  ),
  mainPanel(
   verbatimTextOutput("Model")
  )
 )
)

server <- function(input, output) {
 #--- Create Exogenous Variable 'periods'
 data(Canada)
 canTS <- Canada
 periods <- as.matrix(data.frame(period=ifelse(index(canTS)>1996, 1, 0 ) ) ) 

 #--- Fit the Model
 fit1 <- VAR(Canada, p = 2, type = "none", exogen=periods)

 #-- Make Prediction
 output$Model <- renderPrint({
 periods2 <- as.matrix(data.frame(period = rep(1, input$nAhead)) ) # forecasting window
 predict(fit1, n.ahead=input$nAhead, dumvar=periods2) 
 })
}

shinyApp(ui, server)

我收到以下错误消息:"object periods not found"。我不明白为什么 predict 函数不接受 dumvar 提供的新数据矩阵。知道如何使它工作吗?谢谢。

行后

periods <- as.matrix(data.frame(period=ifelse(index(canTS)>1996, 1, 0 ) ) ) 

只需添加以下行

assign("periods",periods, envir = .GlobalEnv)

然后就可以了