r语言 - 如何根据列的唯一值从数据帧创建时间序列列表?



创建的数据示例

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))

如何创建基于上述数据帧上的子产品的列车/测试拆分时间序列列表?共有192行和4个子产品,因此每个子产品48行意味着4个时间序列,但由于训练和测试拆分,我希望列表中有8个元素。

编辑:

for(i in unique(dfone$subproduct)) {
nam <- paste("df", i, sep = ".")
assign(nam, dfone[dfone$subproduct==i,])
}
list_df <- list(df.1,df.2,df.x,df.y) %>%
lapply( function(x) x[(names(x) %in% c("date", "actuals"))])
for (i in 1:length(list_df)) {
assign(paste0("df", i), as.data.frame(list_df[[i]]))
}
combined_dfs <- merge(merge(merge(df1, df2, by='date', all=T), df3, 
by='date', all=T),df4,by="date",all=T)
colnames(combined_dfs) <-  
c("date","actualB1","actualB2","actualAx","actualAy")

list_ts <- 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
list_ts <- do.call("rbind", list_ts)  #Creates a list of time series

以上就是我想要的,但是有没有更简单的方法来完成merge(merge(部分?

类似的东西?

library(dplyr)
train_frac = 0.8
dfone_split <- dfone %>%
mutate(set = sample(c("train", "test"), n(), replace = TRUE, 
prob = c(train_frac, 1 - train_frac)))
dfone_train <- dfone_split %>% filter(set == "train")
dfone_test <- dfone_split %>% filter(set == "test")

您还可以看看rsample软件包,它提供了多种控制拆分的方法,例如在窗口内使用时间采样。

最新更新