【问题标题】:VAR model with exogenous variable doesn't work in Shiny具有外生变量的 VAR 模型在 Shiny 中不起作用
【发布时间】:2018-05-25 14:35:16
【问题描述】:

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

我收到以下错误消息:“未找到对象期间”。我不明白为什么predict 函数不接受dumvar 提供的新数据矩阵。知道如何使它工作吗?谢谢。

【问题讨论】:

    标签: r shiny prediction


    【解决方案1】:

    行后

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

    只需添加以下行

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

    然后就可以了

    【讨论】:

    • 谢谢,它按预期工作。我希望这个 assign 到 GlobalEnv 不会对我复杂模型中的其他反应值造成麻烦。不错的解决方案!
    • 你可以随时使用&lt;&lt;-
    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2015-06-01
    相关资源
    最近更新 更多