具有外生变量的VAR模型在Shiny

时间:2018-05-25 14:35:17

标签: r shiny prediction

让我们考虑一个带有外生变量的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)

我收到以下错误消息:&#34;找不到对象句点&#34;。我不明白为什么predict函数不接受dumvar提供的新数据矩阵。知道如何使这个工作吗?谢谢。

1 个答案:

答案 0 :(得分:2)

行后

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

只需添加以下内容

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

然后它可以工作