RStudio-Shiny代码可以逐行工作(Ctrl + Enter),但不能与“运行应用程序”按钮一起使用

时间:2019-05-21 20:52:46

标签: shiny rstudio run-app

在RStudio中,如果我逐行使用Ctrl + Enter运行以下Shiny代码,则它们可以正常工作。但是,如果我使用“运行应用程序”按钮运行整个代码,则会产生此错误:

ts(x)中的错误:“ ts”对象必须具有一个或多个观察结果

我认为这是由于“ lambda”参数引起的,但我不知道为什么。任何帮助表示赞赏。

“ data.csv”的链接为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)

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

1 个答案:

答案 0 :(得分:0)

autoplot()返回ggplot对象。但是您的输出$ 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)
    })
}
可以使用ggplotly函数轻松地转换

ggplot对象,但是不幸的是,转换后的plotly自动绘图图丢失了预测区域。您可以像这样验证它:

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))
    })
}

添加

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

autoplotly()函数可以将自动绘图对象转换为大致正确的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)

可以看到预测区域,并通过鼠标悬停事件显示高/低80%的边缘值。

enter image description here