You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

flexdashboard中用shiny的actionButton和eventReactive生成ARIMA预测图失败

问题根因与实现方案

核心报错argument is of length zero来自两个逻辑漏洞:

  1. ARIMA模型运算未绑定按钮点击事件,页面初始化时无输入数据就自动执行
  2. 模型与筛选数据的依赖关系未打通,数据源更新后不会触发模型重算

以下是满足全部需求的完整实现:

完整可运行代码
---
title: "ARIMA预测看板"
output: flexdashboard::flex_dashboard
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(forecast)
library(dplyr)
library(ggplot2)
# 加载原始数据集
raw_data <- read.csv("https://github.com/imlemarque/Data/raw/main/Data.csv")
# 日期字段格式化,可根据实际字段名调整
raw_data$date <- as.Date(raw_data$date)

侧边栏 {.sidebar}

# 时间范围筛选
dateRangeInput("date_range",
               label = "分析时间范围",
               start = min(raw_data$date),
               end = max(raw_data$date))
# 预测周期设置
numericInput("h",
             label = "预测周期数",
             value = 12,
             min = 1)
# 计算触发按钮
actionButton("run", "Start forecasting", class = "btn btn-primary")
分析结果

ARIMA {data-icon="fa-table"}

# 响应式筛选数据
filtered_ts <- reactive({
  raw_data %>%
    filter(date >= input$date_range[1], date <= input$date_range[2]) %>%
    pull(value) %>% # 数值列名可根据实际字段调整
    ts(frequency = 12) # 频率按需调整:月度12、周度52、日度7
})
# 绑定按钮触发ARIMA全流程计算
arima_res <- eventReactive(input$run, {
  # 拦截无效输入,避免空值报错
  req(filtered_ts(), input$h)
  # 自动拟合ARIMA模型
  model <- auto.arima(filtered_ts())
  # 生成预测结果
  fc <- forecast(model, h = input$h)
  # 封装返回所有结果
  list(
    model = model,
    forecast = fc,
    metrics = data.frame(
      指标名称 = c("AIC", "BIC", "RMSE", "MAE"),
      指标值 = round(c(AIC(model), BIC(model), accuracy(fc)[1, c("RMSE", "MAE")]), 4)
    )
  )
})
# 输出预测结果表
renderTable({
  req(arima_res())
  fc <- arima_res()$forecast
  data.frame(
    预测周期 = seq_along(fc$mean),
    预测值 = round(fc$mean, 2),
    95%置信下限 = round(fc$lower[,2], 2),
    95%置信上限 = round(fc$upper[,2], 2)
  )
})

ARIMA2 {data-icon="fa-line-chart"}

renderPlot({
  req(arima_res())
  autoplot(arima_res()$forecast) +
    theme_bw() +
    labs(title = "ARIMA预测趋势图", x = "时间周期", y = "指标值")
})

模型性能 {data-icon="fa-tachometer-alt"}

renderTable({
  req(arima_res())
  arima_res()$metrics
})
# 逻辑说明
- 使用`eventReactive`将ARIMA全流程运算绑定到`Start forecasting`按钮,仅点击后才执行计算
- `req()`函数自动拦截空输入场景,彻底解决初始化阶段的空参数报错
- 新增「模型性能」标签页自动输出AIC、BIC、RMSE、MAE四项核心评估指标
- 代码中字段名、时间序列频率可根据实际数据集结构按需调整

内容的提问来源于stack exchange,提问作者LeMarque
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:24:03