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

如何将按年份聚合的分组DataFrame转换为ts时间序列对象

如何将分组的年度聚合数据转换为时间序列对象?

你的问题核心在于stats::ts()要求连续无缺失的时间索引,但分组数据中存在年份断层(比如Type 1缺少1989、1990年数据),直接转换会导致时间轴错位或报错。以下是具体解决方案:

步骤1:预处理数据,补全缺失年份

先取消分组,为每个Type补全所有年份的记录,缺失的Rolling_Sum用NA填充:

library(tidyverse)
library(stats)

# 取消分组,转换为普通数据框
df <- ungroup(grouped_df)

# 获取数据覆盖的完整年份范围
all_years <- seq(min(df$Year), max(df$Year), by = 1)

# 为每个Type补全所有年份,缺失值填充NA
full_df <- df %>%
  group_by(Type) %>%
  complete(Year = all_years) %>%
  ungroup()

步骤2:生成时间序列对象

根据需求选择以下两种方式:

方式1:按Type生成独立的时间序列列表

适合单独分析每个Type的时序特征:

# 按Type拆分数据并生成ts对象
ts_list <- full_df %>%
  group_split(Type) %>%
  purrr::map(function(sub_df) {
    ts(
      data = sub_df$Rolling_Sum,
      start = min(sub_df$Year),
      end = max(sub_df$Year),
      frequency = 1  # 年度数据频率为1
    )
  })

# 为列表元素命名,方便调用
names(ts_list) <- unique(full_df$Type)

# 查看Type 1的时间序列
ts_list[["Type 1"]]

方式2:生成多变量时间序列

适合对比分析多个Type的时序趋势:

# 转换为宽格式(每个Type作为一列)
wide_df <- full_df %>%
  pivot_wider(names_from = Type, values_from = Rolling_Sum) %>%
  arrange(Year)

# 生成多变量ts对象
multi_ts <- ts(
  data = wide_df[, -1],  # 排除Year列
  start = min(wide_df$Year),
  end = max(wide_df$Year),
  frequency = 1
)

# 查看多变量时间序列
multi_ts

关键说明

ts()函数的时间索引是基于连续位置的,如果原始数据有年份缺失,直接转换会跳过缺失年份的位置,导致时间轴与实际年份不匹配。补全缺失年份后,ts才能正确映射每个值到对应的年份。

内容的提问来源于stack exchange,提问作者alec22

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:05:28