RStudio-Shiny 代码逐行工作 (Ctrl+Enter),但不能使用 "Run App" 按钮

RStudio-Shiny code works line-by-line (Ctrl+Enter), but not with the "Run App" button

在 RStudio 中,如果我 运行 使用 Ctrl+Enter 逐行地使用下面的 Shiny 代码,它就可以正常工作。但是,如果我 运行 整个代码使用 "Run App" 按钮,它会生成此错误:

ts(x) 错误:'ts' 对象必须有一个或多个观察结果

我认为这是由于 "lambda" 参数,但我不明白为什么。任何帮助表示赞赏。

"data.csv" 的 link 是 https://www.dropbox.com/s/p1bhacdg8j1qx42/data.csv?dl=0

====================================

library(shiny)
library(shinydashboard)
library(plotly)
library(forecast)

df <- read.csv("data.csv")
demand <- ts(df$demand, start = c(1995, 1), frequency = 12)

lbd <- BoxCox.lambda(demand, lower=-5, upper=5)
m <- ar(BoxCox(demand,lambda=lbd))
fit_BC <- forecast(m, h=12, lambda=lbd)

ui <- dashboardPage(
  dashboardHeader(title = "Plot"),
  dashboardSidebar(disable = TRUE),
  dashboardBody(fluidRow(column(width = 12, box(plotlyOutput("forecast_plots"),width = NULL))))
)

server <- function(input, output) {
  output$forecast_plots <- renderPlotly({
    autoplot(fit_BC)
  })
}

shinyApp(ui, server)

==================================

autoplot() returns ggplot 对象。但是你的 output$forecast_plots 需要 plotly 对象(使用 plotlyOutput() 函数)。

工作代码如下:

ui <- dashboardPage(
    dashboardHeader(title = "Plot"),
    dashboardSidebar(disable = TRUE),
    dashboardBody(fluidRow(column(width = 12, box(plotOutput("forecast_plots"),width = NULL))))
)

server <- function(input, output) {
    output$forecast_plots <- renderPlot({
        autoplot(fit_BC)
    })
}

ggplot 对象可以很容易地用ggplotly 函数转换,但不幸的是转换后的plotly autoplot 图形丢失了预测区域。您可以像这样验证它:

ui <- dashboardPage(
    dashboardHeader(title = "Plot"),
    dashboardSidebar(disable = TRUE),
    dashboardBody(fluidRow(column(width = 12, box(plotlyOutput("forecast_plots"),width = NULL))))
)

server <- function(input, output) {
    output$forecast_plots <- renderPlotly({
        ggplotly(autoplot(fit_BC))
    })
}

添加

我找到了 autoplotly 库。https://terrytangyuan.github.io/2018/02/12/autoplotly-intro/

autoplotly()函数可以将autoplot对象转换为大致正确的plotly对象。

library(shiny)
library(shinydashboard)
library(plotly)
library(forecast)
library(autoplotly)

df <- read.csv("c:/Users/010170283/Downloads/data.csv")
demand <- ts(df$demand, start = c(1995, 1), frequency = 12)

lbd <- BoxCox.lambda(demand, lower=-5, upper=5)
m <- ar(BoxCox(demand,lambda=lbd))
fit_BC <- forecast(m, h=12, lambda=lbd)

ui <- dashboardPage(
    dashboardHeader(title = "Plot"),
    dashboardSidebar(disable = TRUE),
    dashboardBody(fluidRow(column(width = 12, box(plotlyOutput("forecast_plots"),width = NULL))))
)

server <- function(input, output) {
    output$forecast_plots <- renderPlotly({
        autoplotly(autoplot(fit_BC))
    })
}

shinyApp(ui, server)

用它可以看到预测区域,hi/lo 80%的边缘值用鼠标悬停事件显示。