问题
Let's consider a VAR model with an exogenous variable to distinguish two periods. This model works perfectly as follows:
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
Problem appears when the Shiny app with slider input (which specifies a forecasting horizon) is used. We can create a simple Shiny app as:
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)
I receive following error message: "object periods not found". I don't understand why the predict
function does not accept a new data matrix supplied by dumvar
. Any idea how to make this working? Thank you.
回答1:
After the line
periods <- as.matrix(data.frame(period=ifelse(index(canTS)>1996, 1, 0 ) ) )
just add the following line
assign("periods",periods, envir = .GlobalEnv)
Then it works
来源:https://stackoverflow.com/questions/50531633/var-model-with-exogenous-variable-doesnt-work-in-shiny