首页 > 解决方案 > 从数据帧列表创建时间序列和测试/训练拆分

问题描述

加载数据跳到下面

library(TSstudio)
 date = seq(as.Date("2019/01/01"), by = "month", length.out = 48)
 
productB = rep("B",48)
productB = rep("B",48)
productA = rep("A",48)
productA = rep("A",48)

subproducts1=rep("1",48)
subproducts2=rep("2",48)
subproductsx=rep("x",48)
subproductsy=rep("y",48)

b1 <- c(rnorm(30,5), rep(0,18))
b2 <- c(rnorm(30,5), rep(0,18))
b3 <-c(rnorm(30,5), rep(0,18))
b4 <- c(rnorm(30,5), rep(0,18))

在这里我们加载数据

dfone <- data.frame("date"= rep(date,4),
             "product"= c(rep(productB,2),rep(productA,2)),
             "subproduct"= c(subproducts1,subproducts2,subproductsx,subproductsy),
             "actuals"= c(b1,b2,b3,b4))

export_list <- split(dfone[1:4], dfone[3])
list_ts <- export_list%>% lapply( function(x) x[(names(x) %in% c("date", "actuals"))])
list_ts[[4]]

有没有办法在一个更优雅的解决方案中完成下面组合的所有步骤?For 循环在全局环境中创建 df1,df2,df3,df4

for (i in 1:length(list_ts)) {
  assign(paste0("df", i), as.data.frame(list_ts[[i]]))
}
combined_dfs <- merge(merge(merge(df1, df2, by='date', all=T), df3, by='date',                 
all=T),df4,by="date",all=T)

combined_dfs <- lapply(combined_dfs, function(t) ts(t,start=c(2019,1),end=c(2021,6), frequency 
= 12)) %>%
  lapply( function(t) ts_split(t,sample.out=(0.2*length(t))))    # creates my train test split
    combined_dfs <- do.call("rbind", combined_dfs)  #Creates a list of time series

我正在从我的列表中创建新的 df 对象以组合成一个 df,这样我就可以创建时间序列并训练测试分区。我可以像上面那样做,但我不想在将来手动输入来合并我的所有数据框。如果我有多个子产品,我将拥有大量需要合并到一个 df 中的新数据帧。有没有办法使用 R 包更自动化或在几行代码中做到这一点?

简单地说,我希望我的数据帧列表包含训练/测试拆分的时间序列列表。

标签: rloopsvectortime-seriesdata-manipulation

解决方案


推荐阅读