从 DataFrame R 中的列创建时间序列对象

Create Time Series Objects from Columns in DataFrame R

如果我有这样设置的数据框

 print(df3)
         date actuals actuals2 actuals3 actuals4
1  2019-01-01     193   33        39        33
2  2019-02-01     200   55        109       44

我正在尝试类似下面的方法,但效果不佳

tots <- function(v){ 
ts(v,start=c(2019,1),end=c(2021,6),frequency=12)
}

for (i in 2:ncol(df3)){
 df_ts[i] <- tots(df3[,i])

}

如何为每一列创建一个时间序列变量 (actuals,actuals2,actuals3,actuals4) 以便我有 4 个单独的 ts() 对象?

我认为最简单的方法是从 {zoo} 通过 xts,然后使用 as.ts() 转换为 ts。参数 FUN 指定一个函数来解释 data.frame.

中的日期

编辑以解决评论

  • 您可以使用默认附加的统计信息中的 window() 在训练和测试之间拆分数据。

  • 在循环中,可以使用assing()语法定义新对象。

  • 就个人而言,我会避免使用 ts 对象(或尽可能晚地转换为)。对于数据预处理,有一些包可能会让您的生活更轻松一些,例如 modeltime and the forecast package,仅举几例。

library(zoo)
library(dplyr)

df3 <- tribble(
  ~date,       ~actuals, ~actuals2, ~actuals3, ~actuals4, 
  "2019-01-01",     193,        33,        39,        33, 
  "2019-02-01",     200,        55,       109,        44,
  "2019-03-01",     320,        15,        19,        22,
  "2019-04-01",     218,        25,       209,        33)

ts_tmp <- as.ts(read.zoo(df3, FUN = as.yearmon))
ts_tmp
#>          actuals actuals2 actuals3 actuals4
#> Jan 2019     193       33       39       33
#> Feb 2019     200       55      109       44
#> Mar 2019     320       15       19       22
#> Apr 2019     218       25      209       33


first_date <- df3$date %>% as.yearmon() %>% first() %>% as.numeric()
last_date <- df3$date %>% as.yearmon() %>% last() %>% as.numeric()


ts_tmp_train <- window(ts_tmp, start = first_date, end = first_date + 2/12)
ts_tmp_test <- window(ts_tmp, start = first_date + 3/12, end = last_date)
# note the division by the frequency, where each unit means a whole year


for (i in 1:ncol(ts_tmp)) {
  assign(paste0("ts_act_train", i), ts_tmp_train[, i])
  assign(paste0("ts_act_test", i), ts_tmp_test[, i])
}

ts_act_train1
#>      Jan Feb Mar
#> 2019 193 200 320
ts_act_test1
#>      Apr
#> 2019 218