Data Example Created
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))
Created the dataframe
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))
How can I create list of time series with train/test split based off subproducts on the above dataframe? There is 192 rows, and 4 subproducts, so 48 rows per subproduct implying 4 time series but I want 8 elements in a list because of train and test split.
Edit:
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
Above is pretty much what I want, however is there an easier way to do the merge(merge() part?