【问题标题】:Time Series by group按组的时间序列
【发布时间】:2026-02-15 15:05:04
【问题描述】:

我有一个示例数据框 x 如下:

x <- data.frame(Name = rep(c("Tom", "Mike"), each = 3), Year = rep(c(2017,2018,2019), each = 1), value = c(1,2,3,4,5,6))

我想运行一个时间序列模型来预测每个名字在 2020 年的价值(此处为 Tom 和 Mike)。为此,首先我必须将数据帧 x 转换为时间序列。但是,我不知道如何按组(组 = 名称)创建时间序列。下面的代码产生了奇怪的系列。

ts(runs_reshaped$value, frequency = 1, start = c(2017,1))

任何帮助将不胜感激!

谢谢!

【问题讨论】:

  • 什么是runs_reshaped
  • ts 可以处理多个时间序列,如果数据被正确重塑 - runs_reshaped <- reshape(x, idvar="Year", timevar="Name", direction="wide") 然后ts(runs_reshaped[-1], start=c(2017,1))
  • 我会查看tsibble 包。他们使用key 的概念来识别存储在同一个表中的多个时间序列。然后您可以使用fablefabletools 进行时间序列分析。

标签: r


【解决方案1】:

我们可以通过“名称”将split 转换为list,然后在list 内创建ts

lst1 <- split(x, x$Name)
lapply(lst1, function(u) ts(u$value, frequency = 1, start = c(u$year[1], 1)))

如果我们想以整洁的方式使用它

library(fpp3)
library(dplyr)
library(lubridate)
x %>% 
   mutate(Year = ymd(Year, truncated = 2)) %>%
   as_tsibble(key = Name, index = Year) %>% 
   model(decomp = classical_decomposition(value, type = 'additive')) # apply the models
# A mable: 2 x 2
# Key:     Name [2]
#  Name           decomp
#  <chr>         <model>
#1 Mike  <DECOMPOSITION>
#2 Tom   <DECOMPOSITION>

【讨论】:

    最近更新 更多