-1

Is there a more efficient way to create a future data frame than the loop I am using below; possibly using purrr?

This loop works for me it's run time is just quite inefficient.

prods <- as.vector(unique(sales$ProdLine))
class <- as.vector(unique(sales$Class))
ord <- as.vector(unique(sales$Ordertype))
rep <- as.vector(unique(sales$Rep))
type <- as.vector(unique(sales$Type))

Future_Frame <- data.frame()

for (p in 1:length(unique(prods))) {
 for (c in 1:length(unique(class))) {
  for (o in 1:length(unique(ord))) {
   for (r in 1:length(unique(rep))) {
    for (t in 1:length(unique(type))) {
    
    Dates = seq(max(sales$Date), by = "week", length.out = 52)
    
    d_table <-  Dates %>% as.data.frame() %>% 
      mutate(ProdLine = prods[[p]],
             Class = class[[c]],
             OrderType = ord[[o]],
             Type = type[[t]],
             rep = rep[[r]])
          
    Future_Frame <- rbind(Future_Frame, d_table)
    
    }
   }
  }
 }
}

'''
KBE11416
  • 127
  • 7
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. It looks like you are trying to do something like `expand.grid()` though it's unclear since we can't actually run the code it see what it's doing. – MrFlick Sep 02 '21 at 18:55

1 Answers1

2

Try expand.grid() function from the plyr package.

prods <- as.vector(unique(sales$ProdLine))
class <- as.vector(unique(sales$Class))
ord <- as.vector(unique(sales$Ordertype))
rep <- as.vector(unique(sales$Rep))
type <- as.vector(unique(sales$Type))

library(plyr)
Future_Frame = expand.grid(seq(max(sales$Date), by = "week", length.out = 52)
                           ,prods
                           ,class
                           ,ord
                           ,rep
                           ,type)
Alejo
  • 315
  • 1
  • 10